ente/auth/lib/locale.dart

76 lines
2.2 KiB
Dart
Raw Permalink Normal View History

2023-04-07 08:59:27 +00:00
import 'package:flutter/cupertino.dart';
import 'package:shared_preferences/shared_preferences.dart';
2023-02-07 07:23:04 +00:00
// list of locales which are enabled for auth app.
// Add more language to the list only when at least 90% of the strings are
// translated in the corresponding language.
2023-02-13 07:10:33 +00:00
const List<Locale> appSupportedLocales = <Locale>[
2023-05-07 04:31:23 +00:00
Locale('de'),
2023-02-07 07:23:04 +00:00
Locale('en'),
2023-05-07 04:31:23 +00:00
Locale('es', 'ES'),
Locale('fa'),
2023-04-07 08:59:27 +00:00
Locale('fr'),
Locale('it'),
Locale('ja'),
2023-05-07 04:31:23 +00:00
Locale('nl'),
Locale('pl'),
2023-05-07 04:31:23 +00:00
Locale('pt', 'BR'),
Locale('ru'),
Locale('tr'),
2023-05-07 04:31:23 +00:00
Locale("zh", "CN"),
2023-02-07 07:23:04 +00:00
];
Locale localResolutionCallBack(locales, supportedLocales) {
2023-05-07 04:58:21 +00:00
Locale? languageCodeMatch;
final Map<String, Locale> languageCodeToLocale = {
for (Locale supportedLocale in appSupportedLocales)
2023-10-01 15:45:15 +00:00
supportedLocale.languageCode: supportedLocale,
2023-05-07 04:58:21 +00:00
};
2023-02-07 07:23:04 +00:00
for (Locale locale in locales) {
2023-02-13 07:10:33 +00:00
if (appSupportedLocales.contains(locale)) {
2023-02-07 07:23:04 +00:00
return locale;
}
2023-05-07 04:58:21 +00:00
if (languageCodeMatch == null &&
languageCodeToLocale.containsKey(locale.languageCode)) {
languageCodeMatch = languageCodeToLocale[locale.languageCode];
}
2023-02-07 07:23:04 +00:00
}
2023-05-07 04:58:21 +00:00
// Return the first language code match or default to 'en'
return languageCodeMatch ?? const Locale('en');
2023-02-07 07:23:04 +00:00
}
2023-04-07 08:59:27 +00:00
Future<Locale> getLocale() async {
final String? savedValue =
2023-04-07 08:59:27 +00:00
(await SharedPreferences.getInstance()).getString('locale');
// 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;
}
2023-04-07 08:59:27 +00:00
}
return const Locale('en');
}
Future<void> setLocale(Locale locale) async {
2023-04-07 12:10:47 +00:00
if (!appSupportedLocales.contains(locale)) {
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);
}
2023-04-07 08:59:27 +00:00
await (await SharedPreferences.getInstance())
.setString('locale', out.toString());
2023-04-07 08:59:27 +00:00
}