Explorar o código

Locale: Support persisting both lang and countryCode

Neeraj Gupta %!s(int64=2) %!d(string=hai) anos
pai
achega
aece36e82c
Modificáronse 1 ficheiros con 19 adicións e 5 borrados
  1. 19 5
      lib/locale.dart

+ 19 - 5
lib/locale.dart

@@ -22,11 +22,20 @@ Locale localResolutionCallBack(locales, supportedLocales) {
 }
 }
 
 
 Future<Locale> getLocale() async {
 Future<Locale> getLocale() async {
-  final String? savedLocale =
+  final String? savedValue =
       (await SharedPreferences.getInstance()).getString('locale');
       (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');
   return const Locale('en');
 }
 }
@@ -35,6 +44,11 @@ Future<void> setLocale(Locale locale) async {
   if (!appSupportedLocales.contains(locale)) {
   if (!appSupportedLocales.contains(locale)) {
     throw Exception('Locale $locale is not supported by the app');
     throw Exception('Locale $locale is not supported by the app');
   }
   }
+  final StringBuffer out = StringBuffer(locale.languageCode);
+  if (locale.countryCode != null && locale.countryCode!.isNotEmpty) {
+    out.write('_');
+    out.write(locale.countryCode);
+  }
   await (await SharedPreferences.getInstance())
   await (await SharedPreferences.getInstance())
-      .setString('locale', locale.languageCode);
+      .setString('locale', out.toString());
 }
 }