Flutter国际化插件flutter_i18n_plus的使用
Flutter国际化插件flutter_i18n_plus的使用
flutter_i18n_plus
是一个用于Flutter应用的高级国际化包。它提供了一个简单且灵活的方式来管理翻译、日期格式化、货币格式化以及复数形式。
功能特性
- 简单易用的翻译管理,支持嵌套键
- 支持复数形式
- 日期格式化
- 货币格式化
- 动态语言切换
- 支持翻译中的参数
安装
在项目的 pubspec.yaml
文件中添加 flutter_i18n_plus
依赖:
dependencies:
flutter_i18n_plus: ^1.0.0
然后运行以下命令来获取依赖项:
flutter pub get
配置
- 在项目中创建一个名为
assets/translations/
的文件夹。 - 将翻译文件(例如
en.json
和fr.json
)添加到该文件夹中。 - 更新
pubspec.yaml
文件以包含这些资源:
flutter:
assets:
- assets/translations/
使用
初始化
将 MaterialApp
或 CupertinoApp
包裹在 I18nPlusProvider
中:
void main() {
runApp(
I18nPlusProvider(
supportedLocales: [const Locale('en', 'US'), const Locale('fr', 'FR')],
defaultLocale: const Locale('en', 'US'),
translationsPath: 'assets/translations',
child: MyApp(),
),
);
}
简单翻译
使用 t
扩展方法从 BuildContext
访问翻译:
Text(context.t('greeting'))
带参数的翻译
Text(context.t('welcome', args: {'name': 'John'}))
复数形式
使用 p
扩展方法处理复数形式:
Text(context.p('items', itemCount, args: {'count': itemCount.toString()}))
日期格式化
Text(I18nPlus().formatDate(DateTime.now()))
货币格式化
Text(I18nPlus().formatCurrency(1234.56))
语言切换
使用按钮动态更改语言:
ElevatedButton(
onPressed: () {
final newLocale = I18nPlus().currentLocale.languageCode == 'en'
? const Locale('fr', 'FR')
: const Locale('en', 'US');
I18nPlusProvider.of(context).setLocale(newLocale);
},
child: Text('Changer de langue'),
)
示例翻译文件
en.json
{
"greeting": "Hello",
"welcome": "Welcome, {name}!",
"items": {
"one": "{count} item",
"other": "{count} items"
},
"app.title": "I18nPlus Demo",
"increment": "Increment",
"current_date": "Current Date: {date}",
"account_balance": "Account Balance: {balance}"
}
示例代码
以下是完整的示例代码:
import 'package:flutter/material.dart';
import 'package:flutter_i18n_plus/flutter_i18n_plus.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
MyApp({super.key});
[@override](/user/override)
Widget build(BuildContext context) {
return I18nPlusProvider(
supportedLocales: const [Locale('en', 'US'), Locale('fr', 'FR')],
defaultLocale: const Locale('en', 'US'),
translationsPath: 'assets/translations',
child: MaterialApp(
title: 'I18nPlus Demo',
theme: ThemeData(primarySwatch: Colors.blue),
home: const MyHomePage(),
),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key});
[@override](/user/override)
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
void _incrementCounter() {
setState(() {
_counter++;
});
}
[@override](/user/override)
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(context.t('app.title')),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(context.t('greeting', args: {'name': 'Flutter'})),
const SizedBox(height: 20),
Text(
context
.p('counter', _counter, args: {'count': _counter.toString()}),
style: Theme.of(context).textTheme.headlineMedium,
),
const SizedBox(height: 20),
Text(context.t('current_date',
args: {'date': I18nPlus().formatDate(DateTime.now())})),
const SizedBox(height: 20),
Text(context.t('account_balance',
args: {'balance': I18nPlus().formatCurrency(1234.56)})),
const SizedBox(height: 40),
ElevatedButton(
onPressed: () {
final newLocale = I18nPlus().currentLocale.languageCode == 'en'
? const Locale('fr', 'FR')
: const Locale('en', 'US');
I18nPlusProvider.of(context).setLocale(newLocale);
setState(() {}); // 强制重建小部件
},
child: Text(
'${context.t('change_language')} (${I18nPlus().currentLocale.languageCode})'),
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: context.t('increment'),
child: const Icon(Icons.add),
),
);
}
}
更多关于Flutter国际化插件flutter_i18n_plus的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter国际化插件flutter_i18n_plus的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
当然,以下是一个关于如何使用Flutter国际化插件flutter_i18n_plus
的示例代码案例。这个插件可以帮助你在Flutter应用中实现多语言支持。
1. 添加依赖
首先,在你的pubspec.yaml
文件中添加flutter_i18n_plus
依赖:
dependencies:
flutter:
sdk: flutter
flutter_i18n_plus: ^x.y.z # 请使用最新版本号
然后在你的项目根目录下运行flutter pub get
来安装依赖。
2. 创建翻译文件
在你的项目根目录下创建一个assets/i18n
文件夹,并在其中创建不同语言的翻译文件,例如en.json
和zh.json
:
assets/i18n/en.json:
{
"app_name": "My Flutter App",
"greeting": "Hello, %s!"
}
assets/i18n/zh.json:
{
"app_name": "我的Flutter应用",
"greeting": "你好,%s!"
}
3. 配置pubspec.yaml
在pubspec.yaml
中配置你的翻译文件为资产资源:
flutter:
assets:
- assets/i18n/en.json
- assets/i18n/zh.json
4. 初始化FlutterI18nDelegate
在你的main.dart
文件中,初始化FlutterI18nDelegate
:
import 'package:flutter/material.dart';
import 'package:flutter_i18n_plus/flutter_i18n_plus.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: FlutterI18n.translate(context, "app_name"),
localizationsDelegates: [
// 其他本地化代理
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
// 添加FlutterI18nDelegate
FlutterI18nDelegate(
translationLoader: FileTranslationLoader(
basePath: 'assets/i18n',
),
supportedLocales: [
Locale('en', ''),
Locale('zh', ''),
],
fallbackLocale: Locale('en', ''), // 默认语言
),
],
localeResolutionCallback: (locale, supportedLocales) {
// 根据用户设备语言设置应用语言
for (var supportedLocale in supportedLocales) {
if (supportedLocale.languageCode == locale?.languageCode &&
supportedLocale.countryCode == locale?.countryCode) {
return supportedLocale;
}
}
return supportedLocales.first;
},
home: MyHomePage(),
);
}
}
class MyHomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(FlutterI18n.translate(context, "app_name")),
),
body: Center(
child: Text(
FlutterI18n.translate(context, "greeting", args: ["World"]),
),
),
floatingActionButton: FloatingActionButton(
onPressed: () {
// 切换语言示例
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => LanguageSelectorScreen(),
),
);
},
tooltip: 'Change Language',
child: Icon(Icons.language),
),
);
}
}
5. 创建语言选择器页面
创建一个LanguageSelectorScreen
页面,让用户可以选择应用语言:
import 'package:flutter/material.dart';
import 'package:flutter_i18n_plus/flutter_i18n_plus.dart';
class LanguageSelectorScreen extends StatefulWidget {
@override
_LanguageSelectorScreenState createState() => _LanguageSelectorScreenState();
}
class _LanguageSelectorScreenState extends State<LanguageSelectorScreen> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(FlutterI18n.translate(context, "select_language")),
),
body: ListView(
children: [
ListTile(
title: Text(FlutterI18n.translate(context, "english")),
onTap: () {
FlutterI18n.refresh(context, Locale('en', ''));
Navigator.pop(context);
},
),
ListTile(
title: Text(FlutterI18n.translate(context, "chinese")),
onTap: () {
FlutterI18n.refresh(context, Locale('zh', ''));
Navigator.pop(context);
},
),
],
),
);
}
}
确保在你的翻译文件中也添加了select_language
, english
, 和 chinese
等键:
assets/i18n/en.json:
{
"app_name": "My Flutter App",
"greeting": "Hello, %s!",
"select_language": "Select Language",
"english": "English",
"chinese": "Chinese"
}
assets/i18n/zh.json:
{
"app_name": "我的Flutter应用",
"greeting": "你好,%s!",
"select_language": "选择语言",
"english": "英语",
"chinese": "中文"
}
这样,你就完成了在Flutter应用中使用flutter_i18n_plus
插件来实现国际化的设置。用户可以通过点击浮动按钮在语言选择器页面中切换应用语言。