flutter i18n 國際化

原文地址

step 1

安裝Android Studio 插件 Flutter_i18n (當前版本是0.2)ios

step 2

安裝完成以後,重啓 Android Studio,flutter項目下面會出現res/values文件夾git

step 3

點擊同步按鈕,會自動生成lib/generated/i18n.dartgithub

step 4

4.編輯main.dart, 因爲lib/generated/i18n.dart文件有bug,因此localizationsDelegates, localeResolutionCallback部分代碼須要重寫app

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額外須要的步驟 flutter.dev/docs/develo…less

step 5

重啓應用ide

相關文章
相關標籤/搜索