在说flutter国际化前,不得不提到,在uni-app中支持的Vue-i18n,两者有相似之处,也有差异的地方。
本篇借鉴了三篇热门帖子
Flutter中的国际化:如何写一个多语言的App
Flutter国际化完整例子
Internationalization - Make an Flutter application multi-lingual
只记录根据手机系统语言自动转换app语言
1.引入依赖
引入后,保存会自动加入安装此依赖
//pubspec.yaml
dependencies:
flutter:
sdk: flutter
flutter_localizations: #多语言
sdk: flutter
//这里是Http网络请求需要加入的
dio: ^2.1.13 #Http 请求Dio
http: ^0.12.0 #http
json_serializable: ^3.1.0 #json 序列化
json_annotation: ^2.4.0 #json 注释
2.创建翻译json文件和添加配置
我们新建一个和"/lib"同级别的文件夹"/locale",然后在这个文件夹中新建两个文件,分别为"i18n_en.json" 和" i18n_zh.json"。再在"/lib"文件夹下创建和"main.dart"同级的"translation.dart"和"application.dart"。
文件夹树现在是这个样子的:
MyApplication
|
+- android
+- build
+- images
+- ios
+- lib
|
+-main.dart
+-translation.dart
+-application.dart
+- locale
|
+- i18n_en.json
+- i18n_zh.json
+- test
//i18n_zh.json or i18n_en.json
{ "hello" : "你好!" , "hello" : "Hello~" }
在pubspec.yaml继续加入json,引入静态资源
assets:
- locale/i18n_zh.json
- locale/i18n_en.json
//图片也是需要手动加入到assets中的
- images/lake.jpg
- images/number.png
3.main.dart中加入配置
//导入flutter的包
import 'package:flutter_localizations/flutter_localizations.dart';
import 'translation.dart';
import 'application.dart';
void main(){
debugPaintSizeEnabled = !true;
runApp(MyApp());
}
/// 将App设置为Stateful,这让它可以响应刷新事件,调用应用的SetState()
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => new _MyAppState();
}
class _MyAppState extends State {
SpecificLocalizationDelegate _localeOverrideDelegate;
@override
void initState(){
super.initState();
/// 初始化一个新的Localization Delegate,有了它,当用户选择一种新的工作语言时,可以强制初始化一个新的Translations
_localeOverrideDelegate = new SpecificLocalizationDelegate(null);
/// 保存这个方法的指针,当用户改变语言时,我们可以调用applic.onLocaleChanged(new Locale('en',''));,通过SetState()我们可以强制App整个刷新
applic.onLocaleChanged = onLocaleChange;
}
/// 改变语言时的应用刷新核心,每次选择一种新的语言时,都会创造一个新的SpecificLocalizationDelegate实例,强制Translations类刷新。
onLocaleChange(Locale locale){
setState((){
_localeOverrideDelegate = new SpecificLocalizationDelegate(locale);
});
}
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
localizationsDelegates: [
_localeOverrideDelegate, // 注册一个新的delegate
const TranslationsDelegate(), // 指向默认的处理翻译逻辑的库
// 本地化的代理类
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
],
supportedLocales: applic.supportedLocales(),
title: 'Flutter Router',
debugShowCheckedModeBanner: false, //关掉模拟器右上角debug图标
theme: ThemeData(
primarySwatch: Colors.orange,
),
home: Homes(),
//路由表设置
routes: {
'/Second':(BuildContext context) => new SecondPage(),
'/Http':(BuildContext context) => new HttpPage(),
},
);
}
}
......
//Homes()省略了
4.给translation.dart和application.dart添加内容
//application.dart
import 'package:flutter/material.dart';
typedef void LocaleChangeCallback(Locale locale);
class APPLIC {
// List of supported languages
final List supportedLanguages = ['en','zh'];
// Returns the list of supported Locales
Iterable supportedLocales() => supportedLanguages.map((lang) => new Locale(lang, ''));
// Function to be invoked when changing the working language
LocaleChangeCallback onLocaleChanged;
///
/// Internals
///
static final APPLIC _applic = new APPLIC._internal();
factory APPLIC(){
return _applic;
}
APPLIC._internal();
}
APPLIC applic = new APPLIC();
//translation.dart
import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart' show rootBundle;
import 'application.dart';
class Translations {
Translations(Locale locale) {
this.locale = locale;
_localizedValues = null;
}
Locale locale;
static Map _localizedValues;
static Translations of(BuildContext context){
return Localizations.of(context, Translations);
}
String text(String key) {
try {
String value = _localizedValues[key];
if(value == null || value.isEmpty) {
return englishText(key);
} else {
return value;
}
} catch (e) {
return englishText(key);
}
}
String englishText(String key) {
return _localizedValues[key] ?? '** $key not found';
}
static Future load(Locale locale) async {
Translations translations = new Translations(locale);
String jsonContent = await rootBundle.loadString("locale/i18n_${locale.languageCode}.json");
_localizedValues = json.decode(jsonContent);
return translations;
}
get currentLanguage => locale.languageCode;
}
class TranslationsDelegate extends LocalizationsDelegate {
const TranslationsDelegate();
/// 改这里是为了不硬编码支持的语言
@override
bool isSupported(Locale locale) => applic.supportedLanguages.contains(locale.languageCode);
@override
Future load(Locale locale) => Translations.load(locale);
@override
bool shouldReload(TranslationsDelegate old) => false;
}
/// Delegate类的实现,每次选择一种新的语言时,强制初始化一个新的Translations类
class SpecificLocalizationDelegate extends LocalizationsDelegate {
final Locale overriddenLocale;
const SpecificLocalizationDelegate(this.overriddenLocale);
@override
bool isSupported(Locale locale) => overriddenLocale != null;
@override
Future load(Locale locale) => Translations.load(overriddenLocale);
@override
bool shouldReload(LocalizationsDelegate old) => true;
}
5.获取翻译
......
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("JSON"),
),
body:Center(
child: Column(
children: [
Text(Translations.of(context).text('hello')) //这里
],
)
),......
补充:如果需要强制转换的话(小编自己没有用到)
//为了强制切换另一种工作语言,只需要一行代码,可以在App的任何地方调用:
applic.onLocaleChanged(new Locale('fr',''));