uygulamamda böyle bir sayfa var: bu sayfadaki sıkıntı fontlar yüklenene kadar uygulamam…
- User
uygulamamda böyle bir sayfa var: bu sayfadaki sıkıntı fontlar yüklenene kadar uygulamam açılmıyor. bu da uygulamamın açılış süresini olumsuz etkiliyor. loglar da böyle: LOG Still loading... {"fontsLoaded": false, "isLoading": true} LOG Still loading... {"fontsLoaded": false, "isLoading": true} LOG Still loading... {"fontsLoaded": false, "isLoading": true} LOG Still loading... {"fontsLoaded": false, "isLoading": true} LOG Still loading... {"fontsLoaded": true, "isLoading": true} LOG Still loading... {"fontsLoaded": true, "isLoading": true}
import React, { createContext, useContext, useState, useEffect } from 'react'; import AsyncStorage from '@react-native-async-storage/async-storage'; import * as Localization from 'expo-localization'; import { I18n } from 'i18n-js'; import { Appearance } from 'react-native'; import { setStatusBarStyle } from 'expo-status-bar'; import { useFonts, NotoNaskhArabic_400Regular, NotoNaskhArabic_600SemiBold, } from '@expo-google-fonts/noto-naskh-arabic'; import { NotoSansArabic_400Regular, NotoSansArabic_600SemiBold, } from '@expo-google-fonts/noto-sans-arabic'; import { Amiri_400Regular, Amiri_700Bold, } from '@expo-google-fonts/amiri'; import { Mirza_400Regular, Mirza_600SemiBold, } from '@expo-google-fonts/mirza';
import { darkTheme } from '../themes/darkTheme'; import { lightTheme } from '../themes/lightTheme'; import { vibrantTheme } from '../themes/vibrantTheme'; import { secretGardenTheme } from '../themes/secretGardenTheme'; import { slateDarkTheme } from '../themes/slateDarkTheme'; import { blackOrangeTheme } from '../themes/blackOrangeTheme';
const i18n = new I18n({ en: require('../locales/en.json'), tr: require('../locales/tr.json'), });
i18n.enableFallback = true;
const ThemeAndLanguageContext = createContext();
// Font ailelerinin regular ve bold versiyonlarını tanımlayalım const FONT_FAMILIES = { Mirza: { regular: 'Mirza_400Regular', bold: 'Mirza_600SemiBold' }, Amiri: { regular: 'Amiri_400Regular', bold: 'Amiri_700Bold' }, NotoNaskhArabic: { regular: 'NotoNaskhArabic_400Regular', bold: 'NotoNaskhArabic_600SemiBold' }, NotoSansArabic: { regular: 'NotoSansArabic_400Regular', bold: 'NotoSansArabic_600SemiBold' }, Poppins: { regular: 'Poppins-Regular', bold: 'Poppins-Bold', italic: 'Poppins-Italic' } };
export const ThemeAndLanguageProvider = ({ children }) => { const [themeType, setThemeType] = useState('light'); const [locale, setLocale] = useState(Localization.locale); const [isLoading, setIsLoading] = useState(true); const [selectedFontFamily, setSelectedFontFamily] = useState('Mirza');
// Google Fonts yükleme const [fontsLoaded, fontError] = useFonts({ Mirza_400Regular, Mirza_600SemiBold, Amiri_400Regular, Amiri_700Bold, NotoNaskhArabic_400Regular, NotoNaskhArabic_600SemiBold, NotoSansArabic_400Regular, NotoSansArabic_600SemiBold, 'Poppins-Regular': require('../../assets/fonts/Poppins-Regular.ttf'), 'Poppins-Bold': require('../../assets/fonts/Poppins-Bold.ttf'), 'Poppins-Italic': require('../../assets/fonts/Poppins-Italic.ttf'), });
// Font yükleme hatası varsa konsola yazdır useEffect(() => { if (fontError) { console.error('Font loading error:', fontError); } }, [fontError]);
useEffect(() => { const loadSettings = async () => { try { const storedTheme = await AsyncStorage.getItem('theme'); const storedLocale = await AsyncStorage.getItem('locale'); const storedFontFamily = await AsyncStorage.getItem('fontFamily');
if (storedTheme) { setThemeType(storedTheme); } else { const defaultTheme = Appearance.getColorScheme(); setThemeType(defaultTheme || 'light'); } if (storedLocale) { setLocale(storedLocale); i18n.locale = storedLocale; } else { const defaultLocale = Localization.locale.startsWith('tr') ? 'tr' : 'en'; i18n.locale = defaultLocale; setLocale(defaultLocale); } if (storedFontFamily && FONT_FAMILIES[storedFontFamily]) { setSelectedFontFamily(storedFontFamily); } } catch (error) { console.error('Error loading settings:', error); } finally { if (fontsLoaded) { setIsLoading(false); } } }; loadSettings();}, [fontsLoaded]);
// Loading ekranını göster if (isLoading || !fontsLoaded) { console.log('Still loading...', { isLoading, fontsLoaded }); return null; }
// Font yükleme hatası varsa fallback font kullan if (fontError) { console.warn('Using fallback font due to loading error'); }
const theme = themeType === 'vibrant' ? vibrantTheme : themeType === 'secretGarden' ? secretGardenTheme : themeType === 'slateDark' ? slateDarkTheme : themeType === 'blackOrange' ? blackOrangeTheme : themeType === 'dark' ? darkTheme : lightTheme;
const changeTheme = async (newThemeType) => { setThemeType(newThemeType); await AsyncStorage.setItem('theme', newThemeType);
// Status bar rengini tema değişimine göre ayarla if (newThemeType === 'dark' || newThemeType === 'slateDark' || newThemeType === 'blackOrange') { setStatusBarStyle('light'); } else { setStatusBarStyle('dark'); }};
const changeLanguage = async (newLocale) => { setLocale(newLocale); i18n.locale = newLocale; await AsyncStorage.setItem('locale', newLocale); };
const updateFontFamily = async (newFontFamily) => { if (FONT_FAMILIES[newFontFamily]) { setSelectedFontFamily(newFontFamily); await AsyncStorage.setItem('fontFamily', newFontFamily); } };
const contextValue = { theme, themeType, locale, setThemeType: changeTheme, changeLanguage, t: (key, options) => i18n.t(key, options), // Font değerlerini güncelliyoruz arabicFont: FONT_FAMILIES[selectedFontFamily].regular, arabicFontBold: FONT_FAMILIES[selectedFontFamily].bold, setFontFamily: updateFontFamily, poppinsRegular: FONT_FAMILIES.Poppins.regular, poppinsBold: FONT_FAMILIES.Poppins.bold, poppinsItalic: FONT_FAMILIES.Poppins.italic, // Mevcut font ailesini de ekleyelim currentFontFamily: selectedFontFamily, // Mevcut font listesini de ekleyelim availableFontFamilies: Object.keys(FONT_FAMILIES), };
return ( <ThemeAndLanguageContext.Provider value={contextValue}> {children} </ThemeAndLanguageContext.Provider> ); };
export const useThemeAndLanguage = () => { const context = useContext(ThemeAndLanguageContext); if (context === undefined) { throw new Error('useThemeAndLanguage must be used within a ThemeAndLanguageProvider'); } return context; };
- Assistant
Uygulamanızın açılış süresini iyileştirmek ve fontların yüklenmesini beklemeksizin kullanıcıya hızlı bir deneyim sunmak için font yüklemesini uygulamanın genel yüklemesinden ayrı hale getirebilirsiniz. Şu anki yapınızda
isLoadingdurumu hem ayarların hem de fontların yüklenmesini beklediği için uygulamanın açılışı gecikiyor. Bu durumu çözmek için aşağıdaki adımları izleyebilirsiniz:1.
isLoadingDurumunu Ayarlamayı Ayarlardan Bağımsız Hale GetirinisLoadingdurumunu yalnızca ayarların yüklenmesi için kullanacak şekilde değiştirebilir ve fontların yüklenmesini bağımsız olarak yönetebilirsiniz. Böylece ayarlar yüklendiğinde uygulama hemen render edilebilir, fontlar ise arka planda yüklenmeye devam eder.2. Font Yüklemesini Bağımsız Hale Getirin ve Fallback Font Kullanın
Fontlar henüz yüklenmemişken kullanıcıya varsayılan sistem fontlarını gösterin. Fontlar yüklendikten sonra özel fontlar otomatik olarak uygulamaya dahil edilir.
3. Kodunuzda Yapılacak Değişiklikler
Aşağıda mevcut
ThemeAndLanguageProviderbileşeninizde yapılması gereken değişiklikleri bulabilirsiniz:import React, { createContext, useContext, useState, useEffect } from 'react'; import AsyncStorage from '@react-native-async-storage/async-storage'; import * as Localization from 'expo-localization'; import { I18n } from 'i18n-js'; import { Appearance } from 'react-native'; import { setStatusBarStyle } from 'expo-status-bar'; import { useFonts, NotoNaskhArabic_400Regular, NotoNaskhArabic_600SemiBold, } from '@expo-google-fonts/noto-naskh-arabic'; import { NotoSansArabic_400Regular, NotoSansArabic_600SemiBold, } from '@expo-google-fonts/noto-sans-arabic'; import { Amiri_400Regular, Amiri_700Bold, } from '@expo-google-fonts/amiri'; import { Mirza_400Regular, Mirza_600SemiBold, } from '@expo-google-fonts/mirza'; // ... diğer font ve tema importları import { darkTheme } from '../themes/darkTheme'; import { lightTheme } from '../themes/lightTheme'; // ... diğer tema importları const i18n = new I18n({ en: require('../locales/en.json'), tr: require('../locales/tr.json'), }); i18n.enableFallback = true; const ThemeAndLanguageContext = createContext(); // Font ailelerinin regular ve bold versiyonlarını tanımlayalım const FONT_FAMILIES = { Mirza: { regular: 'Mirza_400Regular', bold: 'Mirza_600SemiBold' }, Amiri: { regular: 'Amiri_400Regular', bold: 'Amiri_700Bold' }, NotoNaskhArabic: { regular: 'NotoNaskhArabic_400Regular', bold: 'NotoNaskhArabic_600SemiBold' }, NotoSansArabic: { regular: 'NotoSansArabic_400Regular', bold: 'NotoSansArabic_600SemiBold' }, Poppins: { regular: 'Poppins-Regular', bold: 'Poppins-Bold', italic: 'Poppins-Italic' } }; export const ThemeAndLanguageProvider = ({ children }) => { const [themeType, setThemeType] = useState('light'); const [locale, setLocale] = useState(Localization.locale); const [isSettingsLoading, setIsSettingsLoading] = useState(true); // Yalnızca ayarlar için const [selectedFontFamily, setSelectedFontFamily] = useState('Mirza'); // Google Fonts yükleme const [fontsLoaded, fontError] = useFonts({ Mirza_400Regular, Mirza_600SemiBold, Amiri_400Regular, Amiri_700Bold, NotoNaskhArabic_400Regular, NotoNaskhArabic_600SemiBold, NotoSansArabic_400Regular, NotoSansArabic_600SemiBold, 'Poppins-Regular': require('../../assets/fonts/Poppins-Regular.ttf'), 'Poppins-Bold': require('../../assets/fonts/Poppins-Bold.ttf'), 'Poppins-Italic': require('../../assets/fonts/Poppins-Italic.ttf'), }); // Font yükleme hatası varsa konsola yazdır useEffect(() => { if (fontError) { console.error('Font loading error:', fontError); } }, [fontError]); useEffect(() => { const loadSettings = async () => { try { const storedTheme = await AsyncStorage.getItem('theme'); const storedLocale = await AsyncStorage.getItem('locale'); const storedFontFamily = await AsyncStorage.getItem('fontFamily'); if (storedTheme) { setThemeType(storedTheme); } else { const defaultTheme = Appearance.getColorScheme(); setThemeType(defaultTheme || 'light'); } if (storedLocale) { setLocale(storedLocale); i18n.locale = storedLocale; } else { const defaultLocale = Localization.locale.startsWith('tr') ? 'tr' : 'en'; i18n.locale = defaultLocale; setLocale(defaultLocale); } if (storedFontFamily && FONT_FAMILIES[storedFontFamily]) { setSelectedFontFamily(storedFontFamily); } } catch (error) { console.error('Error loading settings:', error); } finally { setIsSettingsLoading(false); // Ayarlar yüklendi, fontları bekleme } }; loadSettings(); }, []); // Sadece ayarlar yükleniyorsa yükleme ekranı göster if (isSettingsLoading) { console.log('Yükleniyor...', { isSettingsLoading, fontsLoaded }); return null; // Burada minimal bir splash screen gösterebilirsiniz } // Font yükleme hatası varsa fallback font kullan if (fontError) { console.warn('Yükleme hatası nedeniyle fallback font kullanılıyor'); } const theme = themeType === 'vibrant' ? vibrantTheme : themeType === 'secretGarden' ? secretGardenTheme : themeType === 'slateDark' ? slateDarkTheme : themeType === 'blackOrange' ? blackOrangeTheme : themeType === 'dark' ? darkTheme : lightTheme; const changeTheme = async (newThemeType) => { setThemeType(newThemeType); await AsyncStorage.setItem('theme', newThemeType); // Status bar rengini tema değişimine göre ayarla if (newThemeType === 'dark' || newThemeType === 'slateDark' || newThemeType === 'blackOrange') { setStatusBarStyle('light'); } else { setStatusBarStyle('dark'); } }; const changeLanguage = async (newLocale) => { setLocale(newLocale); i18n.locale = newLocale; await AsyncStorage.setItem('locale', newLocale); }; const updateFontFamily = async (newFontFamily) => { if (FONT_FAMILIES[newFontFamily]) { setSelectedFontFamily(newFontFamily); await AsyncStorage.setItem('fontFamily', newFontFamily); } }; const contextValue = { theme, themeType, locale, setThemeType: changeTheme, changeLanguage, t: (key, options) => i18n.t(key, options), // Font değerlerini güncellerken fontsLoaded kontrolü arabicFont: fontsLoaded ? FONT_FAMILIES[selectedFontFamily].regular : 'System', arabicFontBold: fontsLoaded ? FONT_FAMILIES[selectedFontFamily].bold : 'System Bold', setFontFamily: updateFontFamily, poppinsRegular: fontsLoaded ? FONT_FAMILIES.Poppins.regular : 'System', poppinsBold: fontsLoaded ? FONT_Families.Poppins.bold : 'System Bold', poppinsItalic: fontsLoaded ? FONT_Families.Poppins.italic : 'System Italic', currentFontFamily: selectedFontFamily, availableFontFamilies: Object.keys(FONT_FAMILIES), }; return ( <ThemeAndLanguageContext.Provider value={contextValue}> {children} </ThemeAndLanguageContext.Provider> ); }; export const useThemeAndLanguage = () => { const context = useContext(ThemeAndLanguageContext); if (context === undefined) { throw new Error('useThemeAndLanguage must be used within a ThemeAndLanguageProvider'); } return context; };Değişikliklerin Açıklaması:
-
isLoadingDurumunu Ayar Yüklemeye Bağlı Hale Getirdik:isLoadingadlı durumuisSettingsLoadingolarak yeniden adlandırdık ve yalnızca ayarların yüklenmesini beklemek için kullandık.- Bu sayede fontların yüklenmesi tamamlanmasa bile ayarlar yüklendiğinde uygulama render edilebilir.
-
Font Yüklemesini Engelleyen Koşulu Kaldırdık:
if (isLoading || !fontsLoaded)koşulunuif (isSettingsLoading)olarak değiştirdik. Böylece fontların yüklenmesini beklemiyoruz.- Fontlar yüklenene kadar bile uygulama çalışmaya devam eder. Fontlar yüklendiğinde bile uygulama zaten render edilmiş olur.
-
Fontları Kullanırken
fontsLoadedKontrol Ettik:contextValueiçinde font isimlerini belirlerkenfontsLoadeddurumunu kontrol ederek, fontlar yüklenmemişse sistem fontlarını kullanıyoruz. Bu, fontlar yüklendiğinde otomatik olarak özel fontlara geçiş yapılmasını sağlar.
-
Fallback Font Kullanımı:
- Fontlar yüklenmeden önce sistem fontlarını kullanarak, kullanıcıya hemen bir arayüz sunabilirsiniz. Fontlar yüklendikten sonra özel fontlar otomatik olarak uygulanır.
Ekstra İyileştirmeler:
-
Splash Screen Kullanımı: Uygulamanızın açılışında minimal bir splash screen kullanarak, kullanıcıya yükleme işlemi gerçekleşiyormuş gibi bir his verebilirsiniz. Expo kullanıyorsanız, Expo Splash Screen modülünü inceleyebilirsiniz.
-
Fontları Yerel Olarak Paketleme:
expo-google-fontskullanmak fontları dinamik olarak yükleyebilir ve bu da yükleme süresini artırabilir. Fontları projeye dahil ederek (requireile), fontların anında erişilebilir olmasını sağlayabilirsiniz. Bu, fontların yüklenme süresini kısaltabilir. -
Font Yükleme Önceliği: Kullanılacak en kritik fontları öncelikli olarak yükleyebilir ve diğer fontları gerektiğinde dinamik olarak ekleyebilirsiniz.
Bu değişikliklerle, uygulamanızın açılış süresi iyileşir ve kullanıcılar fontlar yüklenirken bile uygulamayı kullanmaya başlayabilirler. Fontlar yüklendikten sonra, özel fontlar otomatik olarak uygulanacaktır.
-