flutter i18n 国际化

原文地址

step 1

安装Android Studio 插件 Flutter_i18n (当前版本是0.2)

step 2

安装完成之后,重启 Android Studio,flutter项目下面会出现res/values文件夹

step 3

点击同步按钮,会自动生成lib/generated/i18n.dart

step 4

4.编辑main.dart, 由于lib/generated/i18n.dart文件有bug,所以localizationsDelegates, localeResolutionCallback部分代码需要重写

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData(
        primarySwatch: Colors.red,
      ),
      localizationsDelegates: [
        S.delegate,
        GlobalMaterialLocalizations.delegate,
        GlobalWidgetsLocalizations.delegate,
      ],
      supportedLocales: <Locale>[
        Locale("en", ""),
        Locale("zh", ""),
        Locale("fr", ""),
        Locale("de", ""),
      ],
      localeResolutionCallback: (Locale locale, Iterable<Locale> supported) {

        bool isSupported(Locale locale) {
          if (locale == null) return false;
          if (supported.contains(locale)) {
            return true;
          } else {
            for (Locale supportedLocale in supported) {
              if (supportedLocale.countryCode == null || supportedLocale.countryCode.isEmpty)
                if (supportedLocale.languageCode == locale.languageCode) return true;
            }
            return false;
          }
        }

        if (!isSupported(locale))
          return supported.first;

        final Locale languageLocale = Locale(locale.languageCode, "");
        if (supported.contains(locale)) return locale;
        else if (supported.contains(languageLocale)) return languageLocale;
        else return supported.first;
      },
      home: MyHomePage(),
    );
  }
}

ios额外需要的步骤
https://flutter.dev/docs/development/accessibility-and-localization/internationalization#appendix-updating-the-ios-app-bundle

step 5

重启应用

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容