前言:
Flutter項目需要支持國際化,就是在app內實時切換不同的語言,滿足不同用戶的需求。Flutter默認支持英文的文本和組件,如果需要添加本地的支持,直接在Plugins引入插件Flutter Intl,就可以初始化intl和添加添加我們想添加的每一種語言。 接下來我簡單總結一下在Flutter項目中如何實現國際化,有需要的話可以參考。
思路:
1.在Plugins引入插件Flutter Intl
2.在pubspec.yaml 文件中添加依賴flutter_localizations
3.初始化intl和添加語言
4.設置MaterialApp語言環境
5.在App內實現語言切換
實現的步驟:
1.在Plugins引入插件Flutter Intl
2.在pubspec.yaml文件中添加依賴flutter_localizations
dependencies:
flutter:
sdk: flutter
flutter_localizations:
sdk: flutter
cupertino_icons: ^1.0.0
provider: ^4.3.1 #用於實時切換語言的狀態管理
3.初始化intl和添加語言
3.1 初始化intl (Tools->Flutter Intl-> Initialize for the Project)
在pubspec.yaml中自動增加字段:
flutter_intl:
enabled: true
在lib目錄下增加 generated 和 l10n一個包( intl_en.arb,添加英文語言)
{
"home": "Home",
"settingLanguage": "Set Language",
"settingLanguageEnglish": "English",
"settingLanguageChinese": "Chinese"
}
3.2添加語言( intl_zh.arb,添加中文語言)
{
"home": "首頁",
"settingLanguage": "設置語言",
"settingLanguageEnglish": "英文",
"settingLanguageChinese": "中文"
}
4.設置MaterialApp語言環境
MaterialApp(
localizationsDelegates: [
GlobalMaterialLocalizations.delegate,
GlobalCupertinoLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
S.delegate
],
supportedLocales: [
const Locale('zh', 'CN'),
const Locale('en', 'US'),
],
)
5.在App內實現語言切換
5.1封裝CurrentLocale方法
import 'package:flutter/material.dart';
class CurrentLocale with ChangeNotifier {
Locale _locale = const Locale('zh','CN');
Locale get value => _locale;
void setLocale(locale)
{
_locale = locale;
notifyListeners();
}
}
5.2設置實時切換語言的狀態管理
runApp(MultiProvider(
providers: [ChangeNotifierProvider(create: (context) => CurrentLocale())],
child: MyApp(),
));
5.3在MaterialApp添加狀態管理
Consumer<CurrentLocale>(
builder: (context, currentLocale, child) {
return MaterialApp(
localizationsDelegates: [
GlobalMaterialLocalizations.delegate,
GlobalCupertinoLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
S.delegate
],
locale: currentLocale.value,//設置首要支持的語言
supportedLocales: [
const Locale('zh', 'CN'),
const Locale('en', 'US'),
],
...
);
},
)
5.4彈出語言切換的對話框
SimpleDialog(
title: Text(S.of(context).settingLanguage),
children: <Widget>[
SimpleDialogOption(
onPressed: () {
Navigator.pop(context, 1);
},
child: Padding(
padding: const EdgeInsets.symmetric(vertical: 6),
child: Text(S.of(context).settingLanguageChinese),
),
),
SimpleDialogOption(
onPressed: () {
Navigator.pop(context, 2);
},
child: Padding(
padding: const EdgeInsets.symmetric(vertical: 6),
child: Text(S.of(context).settingLanguageEnglish),
),
),
],
)
5.5語言切換的方法
if (i != null) {
if (i == 1) {
Provider.of<CurrentLocale>(context, listen: false)
.setLocale(const Locale('zh', "CH"));
} else {
Provider.of<CurrentLocale>(context, listen: false)
.setLocale(const Locale('en', "US"));
}
}
6.總結
在Flutter上已經實現國際化的功能啦,歡迎大家圍觀。源碼地址: https://github.com/wupeilinloveu/flutter_language ,如果有什麼疑問的話,歡迎留言!