请支持原文 http://tryenough.com/flutter-translation
flutter 国际化实现方案
这里提供一份解决方案,和一份可以直接使用的 demo。
1. 添加依赖库
需要用到 flutter_localizations 包,在 pubspec.yaml 文件中添加如下依赖内容:
dependencies:
flutter:
sdk: flutter
flutter_localizations:
sdk: flutter
添加完记得执行获取这个库:
在 terminal 中运行 flutter packages get, 或者在 IntelliJ\Android Studio 中点击’Packages get’
2. 添加多种语言的文件
请支持原文 http://tryenough.com/flutter-translation
在项目的 lib 同级目录下创建 locale 文件夹,并创建几个 json 文件,用来存储不同语言的翻译文案。如下文件结构:
上图中创建了三种语言的 json 文件,你可以根据你的需要创建其他的语言 json 文件。添加翻译内容,如下:i18n_en.json:
{
“about_page_slogan”:”Health starts here”
}
i18n_zh.json:
{
“about_page_slogan”:” 健康从这里开始 ”
}
记得在 pubspec.yaml 文件中添加这几个资源文件:
3. 创建一个工具类,保存当前支持的语言等信息
请支持原文 http://tryenough.com/flutter-translation
locale_util.dart
import ‘package:flutter/material.dart’;
typedef void LocaleChangeCallback(Locale locale);
class LocaleUtil {
// Support languages list
final List<String> supportedLanguages = [‘en’,’zh’, ‘ja’];
// Support Locales list
Iterable<Locale> supportedLocales() => supportedLanguages.map<Locale>((lang) => new Locale(lang, ”));
// Callback for manual locale changed
LocaleChangeCallback onLocaleChanged;
Locale locale;
String languageCode;
static final LocaleUtil _localeUtil = new LocaleUtil._internal();
factory LocaleUtil() {
return _localeUtil;
}
LocaleUtil._internal();
/// 获取当前系统语言
String getLanguageCode() {
if(languageCode == null) {
return “en”;
}
return languageCode;
}
}
LocaleUtil localeUtil = new LocaleUtil();
3. 添加翻译处理类文件
translations.dart
系统提供了 LocalizationsDelegate 类帮助我们监听系统语言的切换,所以我们可以继承 LocalizationsDelegate 类监听语言切换,并在切换时加载不同的 json 文件,来获取不同的语言文案。这里我们的 translations 工具类就是利用这样的原理来加载不同的语言文案:
import ‘package:translation/locale_util.dart’;
import ‘dart:async’;
import ‘dart:convert’;
import ‘package:flutter/material.dart’;
import ‘package:flutter/services.dart’ show rootBundle;
/// Class for Translate
///
/// For example:
///
/// import ‘package:workout/translations.dart’;
///
/// “`dart
/// For TextField content
/// Translations.of(context).text(“home_page_title”);
/// “`
///
/// “`dart
/// For speak string
/// Note: Tts will speak english if currentLanguage[# Tts’s parameter] can’t support
///
/// Translations.of(context).speakText(“home_page_title”);
/// “`
///
/// “home_page_title” is the key for text value
///
class Translations {
Translations(Locale locale) {
this.locale = locale;
_localizedValues = null;
}
Locale locale;
static Map<dynamic, dynamic> _localizedValues;
static Map<dynamic, dynamic> _localizedValuesEn; // English map
static Translations of(BuildContext context) {
return Localizations.of<Translations>(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 _localizedValuesEn[key] ?? ‘** $key not found’;
}
static Future<Translations> load(Locale locale) async {
Translations translations = new Translations(locale);
String jsonContent = await rootBundle.loadString(“locale/i18n_${locale.languageCode}.json”);
_localizedValues = json.decode(jsonContent);
String enJsonContent = await rootBundle.loadString(“locale/i18n_en.json”);
_localizedValuesEn = json.decode(enJsonContent);
return translations;
}
get currentLanguage => locale.languageCode;
}
class TranslationsDelegate extends LocalizationsDelegate<Translations> {
const TranslationsDelegate();
// Support languages
@override
bool isSupported(Locale locale) {
localeUtil.languageCode = locale.languageCode;
return localeUtil.supportedLanguages.contains(locale.languageCode);
}
@override
Future<Translations> load(Locale locale) => Translations.load(locale);
@override
bool shouldReload(TranslationsDelegate old) => true;
}
// Delegate strong init a Translations instance when language was changed
class SpecificLocalizationDelegate extends LocalizationsDelegate<Translations> {
final Locale overriddenLocale;
const SpecificLocalizationDelegate(this.overriddenLocale);
@override
bool isSupported(Locale locale) => overriddenLocale != null;
@override
Future<Translations> load(Locale locale) => Translations.load(overriddenLocale);
@override
bool shouldReload(LocalizationsDelegate<Translations> old) => true;
}
上面的代码我们看到有两个继承自 LocalizationsDelegate 类的代理类,SpecificLocalizationDelegate 类是提供一种让我们强制指定一种位置的方式,通过改变传进来的 local 来达到从新 load 新 json 的方式。如果你没有这种需求,可以只关心 TranslationsDelegate 这种默认方式。
5. 在 main 方法中将代理设置好
请支持原文 http://tryenough.com/flutter-translation
要想监听系统的代理,就需要设置系统位置代理。方法如下:
在 main.dart 方法中设置:
import ‘package:translation/tanslations.dart’;
import ‘package:translation/locale_util.dart’;
import ‘package:flutter/material.dart’;
import ‘package:flutter_localizations/flutter_localizations.dart’;
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new MaterialApp(
title: ‘My Application’,
theme: new ThemeData(
primarySwatch: Colors.blue,
),
localizationsDelegates: [
const TranslationsDelegate(),
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
],
supportedLocales: localeUtil.supportedLocales(),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
_MyHomePageState createState() => new _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage>{
@override
Widget build(BuildContext context){
return new Scaffold(
appBar: new AppBar(
title: new Text(Translations.of(context).text(“about_page_slogan”)),
),
body: Center(
child: Text(Translations.of(context).text(“about_page_slogan”)),
),
);
}
}
请支持原文 http://tryenough.com/flutter-translation
demo 下载地址:http://tryenough.com/flutter-translation