flutter国际化

使用flutter_i18n进行国际化

1、pubspec.yml里增加依赖

dependencies:
  flutter_localizations:
    sdk: flutter
flutter_i18n: ^0.8.2

然后点击packages get

2、命令行进入根目录建一个文件夹assets/i18n

pubspec.yml里增加资源依赖

assets:
  - assets/i18n/

3、在assets/i18n下新建一个zh_CN.json文件,粘贴以下代码,这里是简体中文,所以用zh_CN命名,如果其他语言,就用其他语言命名,但必须用下划线分割,前面是语言,后面是国家

{
  "tabItemTitleHome": "Home"
}

左边是key,右边是文字

4、main.dart里设置delegate

MaterialApp下增加

localizationsDelegates: [
  FlutterI18nDelegate(useCountryCode: true, fallbackFile: 'zh_CN', path: 'assets/i18n'),
  GlobalMaterialLocalizations.delegate,
  GlobalWidgetsLocalizations.delegate,
],

5、使用文字的地方用以下语句替换

FlutterI18n.translate(context, 'tabItemTitleHome')

tabItemTitleHome替换成自己的key

 

6、获取当前locale

Locale currentLocale = Localizations.localeOf(this.context);
print(currentLocale.languageCode);
print(currentLocale.scriptCode);
print(currentLocale.countryCode);

你可能感兴趣的:(Flutter)