diff --git a/lib/src/easy_localization_controller.dart b/lib/src/easy_localization_controller.dart index 494c344b..2e62e2f8 100644 --- a/lib/src/easy_localization_controller.dart +++ b/lib/src/easy_localization_controller.dart @@ -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 supportedLocales, Locale? fallbackLocale) { + List 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; diff --git a/test/easy_localization_test.dart b/test/easy_localization_test.dart index 59e21213..9078d9ef 100644 --- a/test/easy_localization_test.dart +++ b/test/easy_localization_test.dart @@ -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', () {