Flutter 使用intl實現國際化

1.添加依賴

dependencies:
  #...省略無關項
  intl: ^0.15.7 
dev_dependencies:
   #...省略無關項
  intl_translation: ^0.17.2

2.創建必要目錄

首先,在項目根目錄下創建一個i10n-arb目錄,該目錄保存我們接下來通過intl_translation命令生成的arb文件。一個簡單的arb文件內容如下:

{
  "@@last_modified": "2020-04-07T09:25:06.663066",
  "title": "intl demo",
  "@title": {
    "description": "應用標題",
    "type": "text",
    "placeholders": {}
  },
  "testintl": "生存,還是毀滅,這是個問題。 ",
  "@testintl": {
    "description": "生存",
    "type": "text",
    "placeholders": {}
  }
}

然後在lib目錄下創建一個i10n的目錄,該目錄用於保存從arb文件生成的dart代碼文件。

3.實現Localizations和Delegate類

1.在lib/i10n目錄下新建一個“localization_intl.dart”的文件,文件內容如下:

import 'package:fish_redux/fish_redux.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'messages_all.dart'; //1

class AppLocalizations  implements CupertinoLocalizations{
   Locale locale;
  AppLocalizations(this.locale);
  static Future<AppLocalizations> load(Locale locale) {
    final String name =
    locale.countryCode.isEmpty ? locale.languageCode : locale.toString();
    final String localeName = Intl.canonicalizedLocale(name);
    //2
    return initializeMessages(locale.toString())
        .then((Object _) {
          Intl.defaultLocale=localeName;
      return new AppLocalizations(locale);
    });
  }
  /// 基於Map,根據當前語言的 languageCode: en或zh來獲取對應的文案
  static Map<String, BaseLanguage> _localValue = {
    'en' : EnLanguage(),
    'zh' : ChLanguage()
  };
  /// 返回當前的內容維護類
  BaseLanguage get currentLocalized {
    return _localValue[locale.languageCode];
  }
  ///通過 Localizations.of(context,type) 加載當前的 FZLocalizations
  static AppLocalizations of(BuildContext context) {
    return CupertinoLocalizations.of(context);
  }
  @override
  String get selectAllButtonLabel {
    return currentLocalized.selectAllButtonLabel;
  }
  @override
  String get pasteButtonLabel {
    return currentLocalized.pasteButtonLabel;
  }
  @override
  String get copyButtonLabel {
    return currentLocalized.copyButtonLabel;
  }
  @override
  String get cutButtonLabel {
    return currentLocalized.cutButtonLabel;
  }
  @override
  String get todayLabel {
    return "今天";
  }
  static const List<String> _shortWeekdays = <String>[
    '週一',
    '週二',
    '週三',
    '週四',
    '週五',
    '週六',
    '週日',
  ];

  static const List<String> _shortMonths = <String>[
    'Jan',
    'Feb',
    'Mar',
    'Apr',
    'May',
    'Jun',
    'Jul',
    'Aug',
    'Sep',
    'Oct',
    'Nov',
    'Dec',
  ];

  static const List<String> _months = <String>[
    '01月',
    '02月',
    '03月',
    '04月',
    '05月',
    '06月',
    '07月',
    '08月',
    '09月',
    '10月',
    '11月',
    '12月',
  ];
  @override
  String datePickerYear(int yearIndex) => yearIndex.toString() + "年";
  @override
  String datePickerMonth(int monthIndex) => _months[monthIndex - 1];
  @override
  String datePickerDayOfMonth(int dayIndex) => dayIndex.toString() + "日";
  @override
  String datePickerHour(int hour) => hour.toString();
  @override
  String datePickerHourSemanticsLabel(int hour) => hour.toString() + " 小時";
  @override
  String datePickerMinute(int minute) => minute.toString().padLeft(2, '0');
  @override
  String datePickerMinuteSemanticsLabel(int minute) {
    return '1 分鐘';
  }
  @override
  String datePickerMediumDate(DateTime date) {
    return '${_shortWeekdays[date.weekday - DateTime.monday]} '
        '${_shortMonths[date.month - DateTime.january]} '
        '${date.day.toString().padRight(2)}';
  }
  @override
  DatePickerDateOrder get datePickerDateOrder => DatePickerDateOrder.ymd;
  @override
  DatePickerDateTimeOrder get datePickerDateTimeOrder => DatePickerDateTimeOrder.date_time_dayPeriod;
  @override
  String get anteMeridiemAbbreviation => 'AM';
  @override
  String get postMeridiemAbbreviation => 'PM';
  @override
  String get alertDialogLabel => '提示信息';
  @override
  String timerPickerHour(int hour) => hour.toString();
  @override
  String timerPickerMinute(int minute) => minute.toString();
  @override
  String timerPickerSecond(int second) => second.toString();
  @override
  String timerPickerHourLabel(int hour) => '時';
  @override
  String timerPickerMinuteLabel(int minute) => '分';
  @override
  String timerPickerSecondLabel(int second) => '秒';
  String get title {
    return Intl.message(
      'intl demo',
      name: 'title',
      desc: '應用標題',
    );
  }
  String get  testintl  {
    return Intl.message(
      '生存,還是毀滅,這是個問題。',
      name: 'testintl',
      desc: '生存',
    );
  }
}
/// 這個抽象類和它的實現類可以拉出去新建類
/// 中文和英語 語言內容維護
abstract class BaseLanguage {
  String name;
  String selectAllButtonLabel;
  String pasteButtonLabel;
  String copyButtonLabel;
  String cutButtonLabel;
}
class EnLanguage implements BaseLanguage {
  @override
  String name = "This is English";
  @override
  String selectAllButtonLabel = "全選";
  @override
  String pasteButtonLabel = "粘貼";
  @override
  String copyButtonLabel = "複製";
  @override
  String cutButtonLabel = "剪切";
}
class ChLanguage implements BaseLanguage {
  @override
  String name = "這是中文";
  @override
  String selectAllButtonLabel = "全選";
  @override
  String pasteButtonLabel = "粘貼";
  @override
  String copyButtonLabel = "複製";
  @override
  String cutButtonLabel = "剪切";

}

我這個版本是做了改進的,之前在使用intl的時候輸入框長按會報錯,所以添加了處理輸入框長按bug的代碼。

2.在lib/i10n目錄下新建一個“localization_delegate.dart”的文件,文件內容如下:

//Locale代理類
class AppLocalizationsDelegate extends LocalizationsDelegate<CupertinoLocalizations> {
  AppLocalizationsDelegate();
  ///是否支持某個Local
  ///支持中文和英語
  @override
  bool isSupported(Locale locale) {
    return ['zh', 'en'].contains(locale.languageCode);
  }

  ///shouldReload的返回值決定當Localizations Widget重新build時,是否調用load方法重新加載Locale資源
  @override
  bool shouldReload(LocalizationsDelegate<CupertinoLocalizations> old) {
    return false;
  }
  ///根據locale,創建一個對象用於提供當前locale下的文本顯示
  ///Flutter會調用此類加載相應的Locale資源類
  @override
  Future<CupertinoLocalizations> load(Locale locale) {
    println(locale.toString()+"------66666");
    return AppLocalizations.load(locale);
  }
  static AppLocalizationsDelegate delegate = AppLocalizationsDelegate();
}

4.生成arb文件

上面i10n/localization_intl.dart中如果直接拷貝的的代碼會在註釋1跟註釋2那報錯,所以下面來生成註釋位置相關的文件。
1.通過intl_translation包的工具來提取代碼中的字符串到一個arb文件,運行如下命令:

flutter pub pub run intl_translation:extract_to_arb --output-dir=i10n-arb lib/i10n/localization_intl.dart

運行此命令會將在localization_intl.dart中通過Intl API標識的屬性和字符串提取到“i10n-arb/intl_messages.arb”文件中:

{
  "@@last_modified": "2020-04-24T10:21:36.493230",
  "title": "soft_fox",
  "@title": {
    "description": "應用標題",
    "type": "text",
    "placeholders": {}
  },
  "testintl": "生存,還是毀滅,這是個問題。 ",
  "@testintl": {
    "description": "呵呵",
    "type": "text",
    "placeholders": {}
  }
}

對應在localization_intl.dart中的內容爲:


  String get title {
    return Intl.message(
      'soft_fox',
      name: 'title',
      desc: '應用標題',
    );
  }

  String get  testintl  {
    return Intl.message(
      '生存,還是毀滅,這是個問題。 ',
      name: 'testintl',
      desc: '呵呵',
    );
  }
}

此時生成的是默認的Locale資源文件,如果我們現在要支持英文和中文,只需要在該文件同級目錄創建"intl_en.arb"文件和"intl_zh.arb"文件,然後將"intl_messages.arb"的內容拷貝到兩個文件中,接下來將新建的文件中的內容進行翻譯即可,翻譯後的"intl_en.arb"文件內容如下:

{
  "@@last_modified": "2020-04-06T21:24:01.928263",
  "title": "soft_fox",
  "@title": {
    "description": "app title",
    "type": "text",
    "placeholders": {}
  },
  "testintl": "To be, or not to be- that is the question: ",
  "@testintl": {
    "description": "haha",
    "type": "text",
    "placeholders": {}
  }
}

由於在定義的時候使用的是中文,在這裏intl_zh.arb中就可以不做處理。

5.生成dart代碼

最後一步就是根據arb生成dart文件,這裏的dart就是在localization_intl.dart中需要引用的:

flutter pub pub run intl_translation:generate_from_arb --output-dir=lib/i10n --no-use-deferred-loading lib/i10n/localization_intl.dart i10n-arb/intl_*.arb

這句命令會根據我們的arb文件生成對應的dart文件:
在這裏插入圖片描述
最後我們將之前用到的兩句命令合併在一個intl.sh文件中,內容如下:

flutter pub pub run intl_translation:extract_to_arb --output-dir=i10n-arb lib/i10n/localization_intl.dart
flutter pub pub run intl_translation:generate_from_arb --output-dir=lib/i10n --no-use-deferred-loading lib/i10n/localization_intl.dart i10n-arb/intl_*.arb

後面新增新的需要國際話的文字之後直接運行這個intl.sh文件即可。

6.在main.dart中引入我們定義的代理

  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'intl demo',
      debugShowCheckedModeBanner: false,
	//...省略無關項
      localizationsDelegates: [
        AppLocalizationsDelegate(), // 我們定義的代理
        GlobalMaterialLocalizations.delegate,
        GlobalWidgetsLocalizations.delegate,
      ],
      locale: GlobalThemeStyles.themeLocale,
      supportedLocales: <Locale>[
        const Locale('en', 'US'), // 美國英語
        const Locale('zh', 'CN'), // 中文簡體
      ],
     //...省略無關項
    );
  }

到此就完成了國際化的操作。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章