Skip to content

Commit

Permalink
fix strict countryCode problem (#690)
Browse files Browse the repository at this point in the history
  • Loading branch information
PatrickChrestin authored Jun 14, 2024
1 parent e5d0f70 commit 2926e4e
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 2 deletions.
19 changes: 17 additions & 2 deletions lib/src/easy_localization_controller.dart
Original file line number Diff line number Diff line change
Expand Up @@ -72,14 +72,29 @@ class EasyLocalizationController extends ChangeNotifier {
}) {
final selectedLocale = supportedLocales.firstWhere(
(locale) => locale.supports(deviceLocale),
orElse: () => _getFallbackLocale(supportedLocales, fallbackLocale),
orElse: () => _getFallbackLocale(
supportedLocales,
fallbackLocale,
deviceLocale: deviceLocale,
),
);
return selectedLocale;
}

//Get fallback Locale
static Locale _getFallbackLocale(
List<Locale> supportedLocales, Locale? fallbackLocale) {
List<Locale> supportedLocales, Locale? fallbackLocale,
{final Locale? deviceLocale}) {
if (deviceLocale != null) {
// a locale that matches the language code of the device locale is
// preferred over the fallback locale
final deviceLanguage = deviceLocale.languageCode;
for (Locale locale in supportedLocales) {
if (locale.languageCode == deviceLanguage) {
return locale;
}
}
}
//If fallbackLocale not set then return first from supportedLocales
if (fallbackLocale != null) {
return fallbackLocale;
Expand Down
30 changes: 30 additions & 0 deletions test/easy_localization_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -225,6 +225,36 @@ void main() {
zhHans,
);
});

test('select best lenguage match if no perfect match exists', () { // #674
const userDeviceLocale = Locale('en', 'FR');
const supportedLocale1 = Locale('en', 'US');
const supportedLocale2 = Locale('zh', 'CN');

expect(
EasyLocalizationController.selectLocaleFrom(
[supportedLocale1, supportedLocale2],
userDeviceLocale,
fallbackLocale: supportedLocale2,
),
supportedLocale1,
);
});

test('select perfect match if exists', () { // #674
const userDeviceLocale = Locale('en', 'GB');
const supportedLocale1 = Locale('en', 'US');
const supportedLocale2 = userDeviceLocale;

expect(
EasyLocalizationController.selectLocaleFrom(
[supportedLocale1, supportedLocale2],
userDeviceLocale,
fallbackLocale: supportedLocale2,
),
supportedLocale2,
);
});
});

group('tr', () {
Expand Down

0 comments on commit 2926e4e

Please sign in to comment.