1. 安裝Flutter i18n
Flutter i18n是一個(gè)Android Studio的插件。沒有安裝的需要進(jìn)行安裝,如下圖所示巫俺。
安裝后項(xiàng)目的結(jié)構(gòu)如下圖所示:
res/values/strings_en.arb和lib/generated/i18n.dart是自動(dòng)生成的。
2.在res/values目錄下添加strings_zh.arb
strings后面跟的zh必須是Locale的languageCode卷雕。添加完成之后分別在strings_en.arb和strings_zh.arb中添加你要國際化的屬性钱雷,如下所示:
{
"hello": "你好!",
"greetTo": " $name骂铁,見到你非常高興!"
}
{
"hello": "Hello!",
"greetTo": "Nice to meet you, $name!"
}
從上面罩抗,我們發(fā)現(xiàn)flutter i18n插件比起intl方法拉庵,幫我們省了很多東西,我們只需要關(guān)注要國際化的屬性即可澄暮,不在需要關(guān)注生成arb文件和arb文件再生成dart這些步驟名段。
3. 在main中的使用
import 'package:flutter/material.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'generated/i18n.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
String _locale = 'zh';
onChangeLanguage() {
if (_locale == 'en') {
setState(() {
_locale = 'zh';
});
} else {
setState(() {
_locale = 'en';
});
}
}
@override
Widget build(BuildContext context) {
return new MaterialApp(
locale: Locale(_locale, ""),
localizationsDelegates: [
S.delegate,
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
GlobalCupertinoLocalizations.delegate,
],
supportedLocales: S.delegate.supportedLocales,
localeResolutionCallback:
S.delegate.resolution(fallback: new Locale('zh', '')),
home: MyHomePage(this.onChangeLanguage));
}
}
class MyHomePage extends StatelessWidget {
final VoidCallback onChangeLanguage;
MyHomePage(this.onChangeLanguage);
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text(S.of(context).hello),
),
body: new Center(
child: new Text(S.of(context).greetTo('Nina')),
),
floatingActionButton: new FloatingActionButton(
child: new Icon(Icons.language), onPressed: onChangeLanguage));
}
}