添加依赖
将其添加到包的pubspec.yaml文件中:
dependencies: flutter_i18n: ^0.6.3
创建json翻译文件
创建两个或者多个文件,
/assets/i18n/en.json
"title": "Test",
"label": {
"main": "Hello {user}!"
},
"button": {
"clickMe": "Click here"
},
"toastMessage": "You clicked on button!",
"clicked": {
"times-0": "You clicked {times} times!",
"times-1": "You clicked {time} time!",
"times-2": "You clicked {times} times!"
}
}
/assets/i18n/zh.json
{
"title": "测试",
"label": {
"main": "您好 {user}!"
},
"button": {
"clickMe": "Premi qui"
},
"toastMessage": "Hai premuto un bottone!",
"clicked": {
"times-0": "Hai premuto {times} volte!",
"times-1": "Hai premuto {time} volta!",
"times-2": "Hai premuto {times} volte!"
}
}
在pubspec.yaml文件中添加资源配置:
flutter:
uses-material-design: true
assets:
- assets/i18n/
入口文件 主要代码
localizationsDelegates: [
// 本地化的代理类
FlutterI18nDelegate(useCountryCode: false, fallbackFile: 'zh', path: 'assets/i18n'),
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
],
supportedLocales: [
const Locale('en', 'US'), // 美国英语
const Locale('zh', 'CN'), // 中文简体
//其它Locales
],
页面使用
Locale currentLang;
int clicked = 8;
@override
void initState() {
super.initState();
new Future.delayed(Duration.zero, () async {
await FlutterI18n.refresh(context, new Locale('en'));//这里主要设置引入语言包
setState(() {
currentLang = FlutterI18n.currentLocale(context);
});
});
}
Text(FlutterI18n.translate(context, "title")),
改变语言
setState(() {
currentLang.languageCode=='en' ? FlutterI18n.refresh(context, new Locale('zh')) : FlutterI18n.refresh(context, new Locale('en'));
});