苹果的我以前写过,点击链接查看,如果只是通过flutter配置国际化,那只需要把Localizations里面添加需要支持的语言包即可,其他的就不用配置了。
flutter_localizations:
sdk: flutter
Pub get
两种方法,第一种是使用intl插件,第二种是使用JSON文件,先记录第一种,
如下图安装插件,重启IDE
Tools
-> Flutter Intl
-> Initialize for the Project
,如下图所示
supportedLocales: S.delegate.supportedLocales,
localizationsDelegates: const [
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
GlobalCupertinoLocalizations.delegate,
S.delegate
],
默认只有英语,添加其他语言文件:Tools
->Flutter Intl
->Add Locale
,根据需要添加语言,我这里添加简体繁体中文zh_Hans
和zh_Hant
,如下图所示
分别在intl_en.arb
,intl_zh_Hans.arb
,intl_zh_Hant.arb
三个文件中编写英文,简体中文,繁体中文对应的key-value
S.of(context).key
换一下key即可
MyApp
改成StatefulWidget
MyApp
添加静态方法:static _MyAppState *of*(BuildContext context) => context.findAncestorStateOfType<_MyAppState>()!;
_MyAppState
添加属性locale
,添加set方法(赋值包裹setState),MaterialApp添加localeMyApp.of(context).setLocale(Locale.fromSubtags(languageCode: ‘语言‘))
切换语言shared_preferences
本地存储shared_preferences: ^2.0.15
-> Pub get
final prefs = await SharedPreferences.*getInstance*();
prefs.setInt("language", index);
SharedPreferences prefs = await SharedPreferences.*getInstance*();
int? languageIndex = prefs.get("language") as int?;
接下来记录的是json国际化(不推荐,可以直接跳到文章末尾看demo)
supportedLocales:[
const Locale.fromSubtags(languageCode: "zh", scriptCode: "Hans"),
const Locale.fromSubtags(languageCode: "zh", scriptCode: "Hant"),
const Locale.fromSubtags(languageCode: "en"),
]
localizationsDelegates:[
GlobalMaterialLocalizations.delegate,
GlobalCupertinoLocalizations.delegate,
GlobalWidgetsLocalizations.delegate
//上面三个是系统的,这里还要加上一个自己创建的类
GCLocalizationsDelegate.*delegate*
]
localizations.dart
文件(操作国际化的类)i18n.json
文件 (国际化配置文件)i18n.json
依赖,并Pub get
Json文件和上面的arb
文件一样编写key-value
localizations.dart
文件除了下面的代码,还要自己实现json文件中get的方法
class GCLocalizations {
GCLocalizations(this._locale);
final Locale _locale;
static GCLocalizations of(BuildContext context){
return Localizations.of(context, GCLocalizations);
}
static Map> _localizeValues = {};
Future loadJson() async {
//1.加载json文件
final jsonFile = await rootBundle.loadString("assets/json/i18n.json");
//2.解析json文件
Mapmap = json.decode(jsonFile);
_localizeValues = map.map((key, value) => MapEntry(key, value.cast()));
}
class GCLocalizationsDelegate extends LocalizationsDelegate {
static GCLocalizationsDelegate delegate = GCLocalizationsDelegate();
@override
bool isSupported(Locale locale) {
return ["en", "zh"].contains(locale.languageCode);
}
@override
bool shouldReload(covariant LocalizationsDelegate old) {
return false;
}
@override
Future load(Locale locale) async{
final localizations = GCLocalizations(locale);
await localizations.loadJson();
return localizations;
}
}