okaryo.log

Get Device Language Settings in Flutter | okaryo.log

Get Device Language Settings in Flutter

    #Flutter#i18n

Method

You can get the Locale with the localeOf method of the Localizations class, and then you can get the language code by calling languageCode on it.

You can also get the country code with countryCode.

Locale locale = Localizations.localeOf(context);

print(locale); // en_US
print(locale.languageCode); // en
print(locale.countryCode); // US

Error due to incorrect usage

When I first used localeOf, I encountered the following error:

Requested the Locale of a context that does not include a Localizations ancestor.

これはMaterialApp内のlocaleで動的にLocaleを渡そうとしてlocaleOf(context)を使ったことが原因だった。 This was caused by trying to use localeOf(context) to dynamically pass a Locale to the locale property of the MaterialApp.

return MaterialApp(
  localizationsDelegates: const [
    AppLocalizations.delegate,
    GlobalMaterialLocalizations.delegate,
    GlobalWidgetsLocalizations.delegate,
    GlobalCupertinoLocalizations.delegate,
  ],
  supportedLocales: const [
    Locale('en'),
    Locale('ja'),
  ],
  locale: // Error occurs when trying to call localeOf(context) here
  home: // localeOf(context) needs to be called in a Widget below this
);

Since the context of the MaterialApp hierarchy does not yet have Localization information, calling localeOf(context) there results in an error.

To call localeOf(context), it must be within a Widget that is a child of the home property of either a MaterialApp or a CupertinoApp that holds Localization information.

References


Related Posts
Related Posts
Promotion

This site uses Google Analytics.