flutter_translate
Flutter 的国际化 (i18n) 库。
它允许您定义内容的不同语言翻译并轻松切换。

安装
将此添加到您的 package 的 pubspec.yaml 文件中
dependencies:
flutter_translate: ^1.2.5
从命令行 (或从你的编辑器) 安装包
flutter pub get
配置
导入 flutter_translate
import 'package:flutter_translate/flutter_translate.dart';
将 json 本地化文件放在项目内你选择的文件夹中。
默认情况下,flutter_translate 会在项目根目录的 assets/i18n 文件夹中搜索本地化文件。
在 pubspec.yaml 中声明你的资源本地化目录
flutter:
assets:
- assets/i18n
在 main 函数中创建本地化代理,并通过 LocalizedApp 包裹它来启动应用程序。
void main() async
{
var delegate = await LocalizationDelegate.create(
fallbackLanguage: 'en',
supportedLanguages: ['en', 'es_ES', 'fa']);
runApp(LocalizedApp(delegate, MyApp()));
}
如果本地化文件的资源目录与默认目录 (assets/i18n) 不同,你需要指定它
void main() async
{
var delegate = await LocalizationDelegate.create(
fallbackLanguage: 'en',
supportedLanguages: ['en', 'es_ES', 'fa'],
basePath: 'assets/i18n/');
runApp(LocalizedApp(delegate, MyApp()));
}
示例 MyApp
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
var localizationDelegate = LocalizedApp.of(context).delegate;
return LocalizationProvider(
state: LocalizationProvider.of(context).state,
child: MaterialApp(
title: 'Flutter Translate Demo',
localizationsDelegates: [
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
localizationDelegate
],
supportedLocales: localizationDelegate.configuration.supportedLocales,
locale: localizationDelegate.currentLocale,
theme: ThemeData(primarySwatch: Colors.blue),
home: MyHomePage(),
),
);
}
}
用法
翻译字符串
translate('your.localization.key');
带参数翻译;
translate('your.localization.key', args: {'argName1': argValue1, 'argName2': argValue2});
带复数翻译
translatePlural('plural.demo', yourNumericValue);
JSON
"plural": {
"demo": {
"0": "Please start pushing the 'plus' button.",
"1": "You have pushed the button one time.",
"else": "You have pushed the button {{value}} times."
}
}
更改语言
@override
Widget build(BuildContext context) {
...
...
changeLanguage(context, 'en');
...
...
}
你可以在这里查看完整示例
https://github.com/bratan/flutter_translate/blob/master/example/lib/main.dart