flutter i18n 国际化

原文地址

  • 中文
  • English

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("en", ""),
        Locale("zh", ""),
        Locale("fr", ""),
        Locale("de", ""),
      ],
      localeResolutionCallback: (Locale locale, Iterable 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

重启应用

你可能感兴趣的:(flutter i18n 国际化)