Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix strict countryCode problem #690

Merged
merged 3 commits into from
Jun 14, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading