I have my app that is correctly getting device locale from Android and iOS, but not from web. I get the web locale language code as ui.window.locale.languageCode
using ui.dart
package. In my Mac I set the system language to Italian, time zone is set to Italy and Location services set to enabled but when I run my app on Chrome it always return 'en_'.
Is there something I am missing to do?
This is the code in main() :
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
// Locale myLocale = Localizations.localeOf(context);
return MaterialApp(
title: '',
color: Colors.red,
localizationsDelegates: [
const AppLocalizationsDelegate(),
GlobalMaterialLocalizations.delegate,
GlobalCupertinoLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
],
supportedLocales: [
const Locale('en', 'US'),
const Locale('it', 'IT')
// const Locale('es', 'ES'),
],
localeResolutionCallback:
(Locale locale, Iterable<Locale> supportedLocales) {
for (Locale supportedLocale in supportedLocales) {
if (kIsWeb) {
Locale webLocale = Locale(ui.window.locale.languageCode, '');
print('system locale is ${webLocale}');
return webLocale;
} else if (supportedLocale.languageCode == locale.languageCode ||
supportedLocale.countryCode == locale.countryCode) {
print('device Locale is $locale');
return supportedLocale;
}
}
return supportedLocales.first;
},
...
I had the same problem yesterday with iOS and web. I resolved the iOS problem with this answer. I suppose that the issue for web applications will be fixed in the future (web is not considered as a stable Flutter feature).
If you really need to create an internationalized app on iOS, Android and web, you can use this package.
FutureBuilder<Locale>(
future: DeviceLocale.getCurrentLocale(),
builder: (context, localeData) {
if(!localeData.hasData) return Container( color: Colors.white);
Locale locale = localeData.data;
return MaterialApp(
// localizationsDelegates, supportedLocales, ...
// « _ » is the locale detected by flutter
// You should use the locale detected by the library instead
localeResolutionCallback: (_, supportedLocales) {
for (var supportedLocaleLanguage in supportedLocales) {
if (supportedLocaleLanguage.languageCode == locale.languageCode) return supportedLocaleLanguage;
}
// If device not support with locale to get language code then default get first on from the list
return supportedLocales.first;
}
);
},
);
You can call "Localizations.localeOf(context)" to get the locale in a child of the MaterialApp widget.
It seems that this package is currently not compatible with desktop applications.
I didn't check on the "issues" tab of the Flutter Github page if the issue was signaled. Maybe I should signal it this evening.