FunFlutter系列之國際化Intl方案

爲何採用Intl方案

隨着flutter_i18n組件的做者再也不維護,IDE中的插件已被做者從插件市場中下架.原先使用該方案的FunAndroid項目採用了新的Flutter Intl方案android

該方案沒有flutter_i18n方案成熟,在開發中,IDE的插件也尚未開源.在使用中還須要開發者跟隨項目作一些適配,好比下邊會提到的對簡繁體supportedLocales的一些特殊處理git

配置Flutter Intl

1.安裝插件

確保Android Studio 或 VScode安裝有Flutter Intl插件github

目前AS安裝Flutter插件會自動捆綁安裝該插件xcode

安裝插件

2.初始化項目

  1. pubspec.yaml中添加flutter_localizations依賴並執行packages getbash

    # 國際化
    flutter_localizations:
        sdk: flutter
    複製代碼

  2. 在菜單中找到Tools,選擇Flutter Intl,點擊Init for the project app

  3. init結束後,pubspec.yaml中會自動增長如下字段less

    flutter_intl:
        enabled: true
    複製代碼
  4. lib目錄下會新增generatedl10n兩個目錄.ide

    • l10n目錄下爲arb文件
    • generated目錄下爲根據arb文件自動生成如下dart代碼
  5. 新增語言(好比中文)post

    • 經過插件添加arb文件
    • 填入local code 如zh,en,生成arb文件

      若是存在地區,相似漢語下有大陸的簡體zh_CN,港臺的繁體zh_HKzh_TW學習

    • lib/generated/intl/目錄下會生成新的messages_xx.dart
  6. MaterialApp中配置supportedLocaleslocalizationsDelegates

    • localizationsDelegates,加入由Intl插件生成的S.delegate和SDK組件庫的delegate
    • supportedLocales須要手動將en設置爲第一項,保證無適配對應locale時,en爲默認選項.(此到處理並不優雅)
    • 目前插件在簡繁體不完善須要作部分適配
      • localeResolutionCallback回調中手動處理簡繁體

如下爲示例

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      localizationsDelegates: const [
        S.delegate,
        GlobalMaterialLocalizations.delegate,
        GlobalCupertinoLocalizations.delegate,
        GlobalWidgetsLocalizations.delegate
      ],
      // 講en設置爲第一項,沒有適配語言時,英語爲首選項
      supportedLocales: [const Locale('en', ''), ...S.delegate.supportedLocales],
      // 插件目前不完善手動處理簡繁體
      localeResolutionCallback: (locale, supportLocales) {
        // 中文 簡繁體處理
        if (locale?.languageCode == 'zh') {
          if (locale?.scriptCode == 'Hant') {
            return const Locale('zh', 'HK'); //繁體
          } else {
            return const Locale('zh', 'CN'); //簡體
          }
        }
        return null;
      },
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}
複製代碼
  1. iOS須要在xcode中添加Localizations

使用Flutter Intl

  1. 普通使用

    {"content": "內容"}
    S.of(context).content
    複製代碼
  2. 佔位

    {"welcome": "welcome {name}"}
    S.of(context).welcome("phoenixsky")
    複製代碼
  3. 重複佔位

    {"goodStudy": "{good}{good}學習,{day}{day}向上"}
    S.of(context).goodStudy("好", "天")
    複製代碼

  4. 複數形式

    {"getMessageTips": "{howMany, plural, zero{You have no message} one{You have 1 message} other{You have {howMany} messages}}"}
    S.of(context).getMessageTips(2)
    複製代碼

  5. 更多使用方式見intl | Dart Package

相關項目

玩Android客戶端Flutter版

感謝

localizely/flutter-intl-plugin-sample-app

intl | Dart Package

相關文章
相關標籤/搜索