Locale: Support persisting both lang and countryCode

This commit is contained in:
Neeraj Gupta 2023-05-07 09:44:26 +05:30
parent b0734f6d06
commit aece36e82c
No known key found for this signature in database
GPG key ID: 3C5A1684DC1729E1

View file

@ -22,11 +22,20 @@ Locale localResolutionCallBack(locales, supportedLocales) {
}
Future<Locale> getLocale() async {
final String? savedLocale =
final String? savedValue =
(await SharedPreferences.getInstance()).getString('locale');
if (savedLocale != null &&
appSupportedLocales.contains(Locale(savedLocale))) {
return Locale(savedLocale);
// if savedLocale is not null and is supported by the app, return it
if (savedValue != null) {
late Locale savedLocale;
if (savedValue.contains('_')) {
final List<String> parts = savedValue.split('_');
savedLocale = Locale(parts[0], parts[1]);
} else {
savedLocale = Locale(savedValue);
}
if (appSupportedLocales.contains(savedLocale)) {
return savedLocale;
}
}
return const Locale('en');
}
@ -35,6 +44,11 @@ Future<void> setLocale(Locale locale) async {
if (!appSupportedLocales.contains(locale)) {
throw Exception('Locale $locale is not supported by the app');
}
await (await SharedPreferences.getInstance())
.setString('locale', locale.languageCode);
final StringBuffer out = StringBuffer(locale.languageCode);
if (locale.countryCode != null && locale.countryCode!.isNotEmpty) {
out.write('_');
out.write(locale.countryCode);
}
await (await SharedPreferences.getInstance())
.setString('locale', out.toString());
}