Flutter-基于设备的动态语言

时间:2019-03-07 11:34:19

标签: flutter localization

我正在尝试使用Localizations

获取移动的countryCode和languageCode
Math.Round

但是返回“未找到本地化祖先” 。有人知道这样做的正确方法是什么?

2 个答案:

答案 0 :(得分:2)

使用LocaleResolutionCallback获取设备语言环境:

 Widget build(BuildContext context) {
    Locale myLocale ;

    return MaterialApp(
      title: 'Title',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primarySwatch: Colors.blue,       
      ),
      home: LoginPage(),
      localeResolutionCallback: (deviceLocale, supportedLocales) {
      myLocale = deviceLocale ; // here you make your app language similar to device language , but you should check whether the localization is supported by your app
      print(myLocale.countryCode);
      print(myLocale.languageCode);
      }
      localizationsDelegates: [
        GlobalMaterialLocalizations.delegate,
        GlobalWidgetsLocalizations.delegate,
      ],
      supportedLocales: [
        Locale('es' 'ES'),
      ],
    );
  }

答案 1 :(得分:0)

根据 Ibrahim 的回答,我能够解决另一个用例 - 如果您的应用不支持区域设置该怎么办。您如何确保应用程序回退到适当的“基本”语言 - 在我的情况下是“en”。这是我的尝试 - 请随时发表评论。

  MaterialApp(
    localizationsDelegates: [
      AppLocalizations.delegate,
      GlobalMaterialLocalizations.delegate,
      GlobalWidgetsLocalizations.delegate,
      GlobalCupertinoLocalizations.delegate,
    ],
    //ensure that if a locale is not on the list the fallback is 'en'
    localeResolutionCallback: (
      locale,
      supportedLocales,
    ) {
      if (supportedLocales.contains(Locale(locale.languageCode))) {
        return locale;
      } else {
        return const Locale('en', '');
      }
    },
    supportedLocales: [
      const Locale('en', ''),
      const Locale('pl', ''),
    ],