init method
Initializes the locale provider by loading the saved locale preference.
This method should be called early in the application lifecycle, typically in your main widget or app initialization code. It loads the previously selected language code from persistent storage and sets it as the current locale. If no preference exists, it defaults to the first supported locale.
After initialization, it calls notifyListeners() to update any listening widgets with the new locale state.
Example:
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
final prefs = await SharedPreferences.getInstance();
final localeProvider = LocaleProvider(prefs: prefs);
await localeProvider.init();
runApp(MyApp(localeProvider: localeProvider));
}
Implementation
Future<void> init() async {
String? languageCode = _prefs.getString(_selectedLanguageCodeKey);
if (languageCode != null) {
_locale = Locale(languageCode);
} else {
// Default to the first supported locale (e.g., English) if no preference is saved
if (supportedLocales.isNotEmpty) {
_locale = supportedLocales.first;
}
}
notifyListeners();
}