create static method
- Locale? fallback,
Factory async creator: tries to load saved locale, otherwise uses system locale, otherwise falls back to the provided default (if given) or 'en_US'.
Implementation
static Future<LocaleCubit> create({Locale? fallback}) async {
final prefs = await SharedPreferences.getInstance();
// 1) Try to read saved locale
final saved = prefs.getString(_kSavedLocaleKey);
if (saved != null && saved.isNotEmpty) {
final parts = saved.split('_');
if (parts.isNotEmpty) {
final languageCode = parts[0];
final countryCode = parts.length > 1 ? parts[1] : '';
final locale = countryCode.isNotEmpty
? Locale(languageCode, countryCode)
: Locale(languageCode);
return LocaleCubit._(locale);
}
}
// 2) Fallback to system locale (PlatformDispatcher) if available
try {
final systemLocale = PlatformDispatcher.instance.locale;
return LocaleCubit._(systemLocale);
} catch (_) {
// ignore and continue to fallback
}
// 3) Final fallback
final defaultLocale = fallback ?? const Locale('en', 'US');
return LocaleCubit._(defaultLocale);
}