目錄

效果演示

實現(xiàn)步驟
1.添加Flutter Intl插件

2.初始化項目
在Android Studio中點擊Tools->Flutter Intl->Initialize for the Project

會生成如下這些文件

3.添加語言
在Android Studio中點擊Tools->Flutter Intl->Add Locale

添加完之后會生成新添加的文件

4.增加多語言字段
在上面生成的文件中增加字段即可,這里我只加了英語和中文
intl_en.arb
{
"hello": "hello",
"confirm": "confirm",
"cancel": "cancel"
}
intl_zh.arb
{
"hello": "你好",
"confirm": "確認",
"cancel": "取消"
}
5.增加配置
在main.dart中增加如下配置
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
// =============增加的===============
supportedLocales: S.delegate.supportedLocales,
localizationsDelegates: const [
// ... app-specific localization delegate[s] here
S.delegate,
GlobalMaterialLocalizations.delegate,
GlobalCupertinoLocalizations.delegate,
GlobalWidgetsLocalizations.delegate
],
// =============增加的===============
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
6.增加切換語言頁面
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key, required this.title}) : super(key: key);
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
void _incrementCounter() {
setState(() {
_counter++;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: ListView.builder(
itemCount: 3,
itemExtent: 50,
itemBuilder: (BuildContext context, int index){
if(index == 1){
return GestureDetector(
onTap: (){
S.load(Locale.fromSubtags(languageCode: 'zh'));
setState(() {
});
},
child: ListTile(title: Text("中文")),
);
}else if(index == 2){
return GestureDetector(
onTap: (){
S.load(Locale.fromSubtags(languageCode: 'en'));
setState(() {
});
},
child: ListTile(title: Text("英語")),
);
}
return ListTile(title: Text(S.of(context).hello));
}
),
),
floatingActionButton: FloatingActionButton(
onPressed: (){
_incrementCounter();
},
tooltip: 'Increment',
child: const Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}
這里切換語言的關(guān)鍵代碼如下:
S.load(Locale.fromSubtags(languageCode: 'en'));
//切換完更新下狀態(tài)
setState(() {
});