Flutter国际化插件flutter_gettext的使用
Flutter Gettext
This package provides a simple way to translate your Flutter application using gettext.
It is inspired/based on gettext, gettext_parser, and gettext_i18n but doesn’t depend on these packages.
Features
- ✅ Positional arguments
- ✅ Named arguments
- ✅ Plurals
- ✅ Contexts
- ✅ Comments
Usage
Step 1: Add Dependencies
Add this package and flutter_localizations
to your pubspec.yaml
:
flutter pub add flutter_gettext
flutter pub add flutter_localizations --sdk=flutter
Step 2: Configure Assets
In pubspec.yaml
, add assets/i18n/
as an asset folder:
flutter:
assets:
- assets/i18n/
Step 3: Place Translation Files
Place your translation files in the assets/i18n/
folder:
$ ls assets/i18n/
en.po
de.po
de_AT.po
Step 4: Initialize Translations in Your Application
In your application file, declare supported locales and initialize translations:
import 'package:flutter/material.dart';
import 'package:flutter_gettext/flutter_gettext/context_ext.dart';
import 'package:flutter_gettext/flutter_gettext/gettext_localizations_delegate.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
Future<void> main() async {
runApp(
const App(),
);
}
class App extends StatelessWidget {
const App({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
locale: const Locale('de'),
supportedLocales: const [
Locale('en'),
Locale('de'),
Locale('de_AT'),
],
localizationsDelegates: [
GettextLocalizationsDelegate(),
GlobalMaterialLocalizations.delegate,
GlobalCupertinoLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
],
home: Builder(builder: (context) {
return Scaffold(
body: Center(
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
mainAxisSize: MainAxisSize.min,
children: [
Text(
context.translate(
'There is {0} apple',
keyPlural: 'There are {0} apples',
pArgs: [1],
),
),
Text(
context.translate(
'There is {0} apple',
keyPlural: 'There are {0} apples',
pArgs: [2],
),
),
Text(
context.translate(
'You have {message_count} message',
keyPlural: 'You have {message_count} messages',
nArgs: {'message_count': 1},
),
),
Text(
context.translate(
'You have {message_count} message',
keyPlural: 'You have {message_count} messages',
nArgs: {'message_count': 3},
),
),
],
),
),
);
}),
);
}
}
Step 5: Translate Strings
In files where you want to translate a string:
import 'package:gettext_i18n/gettext_i18n.dart';
Text(context.translate('There is {0} apple', keyPlural: 'There are {0} apples', pArgs: [1]));
// output: There is 1 apple
// output(de): Es gibt 1 Apfel
Text(context.translate('There is {0} apple', keyPlural: 'There are {0} apples', pArgs: [2]));
// output: There are 2 apples
// output(de): Es gibt 2 Äpfel
Text(
context.translate(
'You have {message_count} message',
keyPlural: 'You have {message_count} messages',
nArgs: {'message_count': 1},
),
);
// output: You have 1 message
// output(de): Du hast 1 Nachricht
Text(
context.translate(
'You have {message_count} message',
keyPlural: 'You have {message_count} messages',
nArgs: {'message_count': 3},
),
);
// output: You have 3 messages
// output(de): Du hast 3 Nachrichten
PO Files Structure
Here is an example of a .po
file structure:
msgid ""
msgstr ""
"Content-Type: text/plain; charset=UTF-8\n"
"Plural-Forms: nplurals=2; plural=(n != 1);\n"
"language: en\n"
msgid "Hello"
msgstr "Hello"
# Comments are ignored
msgid "Welcome to my app"
msgstr "Welcome to my app"
# Named argument implementation
msgid "You have {message_count} message"
msgid_plural "You have {message_count} messages"
msgstr[0] "You have {message_count} message"
msgstr[1] "You have {message_count} messages"
# Positional argument implementation
msgid "There is {0} apple"
msgid_plural "There are {0} apples"
msgstr[0] "There is {0} apple"
msgstr[1] "There are {0} apples"
Additional Information
.po
files can be edited by hand, but it’s preferable to use an editor or an online service to manage them.
更多关于Flutter国际化插件flutter_gettext的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter国际化插件flutter_gettext的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
在Flutter应用中实现国际化(i18n)可以通过使用flutter_gettext
插件来完成。以下是一个简单的代码案例,展示了如何设置和使用flutter_gettext
插件进行国际化。
1. 添加依赖
首先,在你的pubspec.yaml
文件中添加flutter_gettext
的依赖:
dependencies:
flutter:
sdk: flutter
flutter_gettext: ^x.y.z # 替换为最新版本号
然后运行flutter pub get
来安装依赖。
2. 创建语言文件
在你的项目根目录下创建一个locales
文件夹,并在其中为每个支持的语言创建对应的YAML文件。例如,创建en.yaml
和zh.yaml
文件:
locales/en.yaml:
app_name: My App
greeting: Hello, %s!
locales/zh.yaml:
app_name: 我的应用
greeting: 你好,%s!
3. 配置Flutter应用
在你的main.dart
文件中,进行以下配置:
import 'package:flutter/material.dart';
import 'package:flutter_gettext/flutter_gettext.dart';
void main() {
// 初始化FlutterGettext
FlutterGettext.initialize(
appName: 'my_app',
localeFiles: {
'en': 'locales/en.yaml',
'zh': 'locales/zh.yaml',
},
defaultLocale: 'en',
);
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: FlutterGettext.tr('app_name'), // 使用国际化字符串
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(),
localizationsDelegates: [
FlutterGettext.delegate,
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
],
supportedLocales: [
Locale('en', ''),
Locale('zh', ''),
],
locale: Locale(FlutterGettext.locale.languageCode, ''), // 设置当前语言
);
}
}
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(FlutterGettext.tr('app_name')),
),
body: Center(
child: Text(
FlutterGettext.tr('greeting', args: ['Flutter']), // 使用带有参数的国际化字符串
),
),
floatingActionButton: FloatingActionButton(
onPressed: () {
// 切换语言示例
setState(() {
FlutterGettext.locale =
FlutterGettext.locale.languageCode == 'en'
? Locale('zh')
: Locale('en');
});
},
tooltip: 'Switch Language',
child: Icon(Icons.translate),
),
);
}
}
4. 运行应用
现在你可以运行你的Flutter应用,并看到初始化为默认语言(例如英语)的界面。通过点击浮动操作按钮(FAB),你可以切换语言并看到界面文本的更新。
总结
这个代码案例展示了如何使用flutter_gettext
插件在Flutter应用中实现基本的国际化功能。通过创建语言文件、配置Flutter应用以及使用FlutterGettext
的相关方法来加载和使用国际化字符串,你可以轻松地为你的应用添加多语言支持。