Flutter本地化字符串管理插件app_strings的使用
Flutter本地化字符串管理插件app_strings的使用
app_strings
是一个用于管理和生成多语言字符串文件的 Flutter 插件。通过这个插件,你可以将所有语言的字符串集中在一个 Dart 文件中,并生成相应的 JSON 文件或 easy_localization 加载器类。
特性
- 在单个 Dart 文件中合并翻译
- 为每个区域生成 JSON 文件
- 生成 easy_localization 加载器类
- 生成包含键路径的键文件
- 从 JSON 文件导入新区域
- 从源文件中移除区域
- 使用 watch 命令持续生成文件
开始使用
首先,在 pubspec.yaml
文件中添加 app_strings
和 build_runner
依赖:
dependencies:
app_strings: latest
dev_dependencies:
build_runner: latest
# 如果你打算使用 easy_localization
dependencies:
app_strings: latest
easy_localization: latest
使用步骤
- 创建一个 Dart 文件
lib/lang/app_strings_source.dart
并复制以下代码:
// ignore_for_file: non_constant_identifier_names, type_annotate_public_apis
import 'package:app_strings/app_strings.dart';
@AppStringsConfig(json: true, easyLoader: true)
class AppStringsSource {
var user = (
gender: (
male: (en_US: "Hi man {} ;)",),
female: (en_US: "Hello girl :)",),
other: (en_US: "Hello {}",),
),
money: (
zero: (en_US: "You not have money",),
one: (en_US: "You have {} dollar",),
many: (en_US: "You have {} dollars",),
other: (en_US: "You have {} dollars",),
),
);
var incomeTransaction = (
fields: (
amount: (en_US: "Price",),
paymentDate: (en_US: "Payment Date",),
),
actions: (
update: (en_US: "Edit",),
detail: (en_US: "Detail",),
addTag: (en_US: "Add Tag",),
),
validations: (
amount: (
notNull: (en_US: "You must enter an amount",),
lessThen: (en_US: "Amount must be less than 100",),
),
),
);
var expenseTransaction = (
fields: (
amount: (en_US: "Price",),
paymentDate: (en_US: "Payment Date",),
),
);
}
重要提示:
- 字段应为 Record 类型。
- 最后一个节点(值节点)应包含区域作为参数名,值应为字符串。
zero
,one
,two
,few
,many
,other
,male
,female
是保留词,它们应作为值节点的第一个父节点。- 如果你使用了这些保留词且正在使用 easy_localization 包,则必须有
other
关键字。
- 运行以下命令以生成文件:
dart run build_runner build --delete-conflicting-outputs
生成的文件包括:
app_strings_source.en_US.json
是一个可以与 easy_localization 或其他支持 JSON 资产的包一起使用的资源文件。app_strings_source.loader.dart
是一个 easy_localization 加载器文件,可以用来加载翻译。app_strings_source.key.dart
是一个包含AppStrings
类及其键的 Dart 文件,用于访问翻译。
AppStringsConfig 参数
以下是 AppStringsConfig
的参数说明:
参数名称 | 类型 | 默认值 | 描述 |
---|---|---|---|
keyClassName | String | AppStrings | 键类的名称 |
easyLoader | bool | false | 生成 easy loader 类 |
json | bool | false | 为每个区域生成 JSON 文件 |
remove | String? | null | 从源文件中移除某个区域 |
import | Import? | null | 从 JSON 文件导入新的区域 |
addRegionComments | bool | false | 添加区域注释到生成的 Dart 文件中,以便在 VSCode 中使用 Colored Regions 插件 |
导入新区域
你可以通过 JSON 文件导入一个新的区域。当导入一个新的区域时,文件会再次生成并包含新的翻译。
import 'package:app_strings/app_strings.dart';
@AppStringsConfig(import: Import(locale: "en_US", path: "lib/lang/imports/en_US.json", json: true, easyLoader: true))
class AppStringsSource {
// 字段 ...
}
警告:
导入后应移除 import
参数。
移除现有区域
你可以使用 AppStringsConfig
注解的 remove
参数从源文件中移除现有的区域。
import 'package:app_strings/app_strings.dart';
@AppStringsConfig(remove: "en_US", json: true, easyLoader: true)
class AppStringsSource {
// 字段 ...
}
监视模式
使用以下命令可以监视源文件并在工作时自动重新生成文件:
dart run build_runner watch --delete-conflicting-outputs
如果你使用的是 localization_pro
包,可以安装新的 JSON 文件并在应用上即时查看更改,而无需重启应用。
源文件位置
默认的源文件位置是 lib/lang/SOURCE_FILE_NAME.dart
和 lib/generated/SOURCE_FILE_NAME.dart
。如果你将源文件放在这些位置,不需要指定源文件位置。
如果要更改源文件位置,可以在项目的根目录创建一个 build.yaml
文件,并在此文件中指定自定义路径。例如:
targets:
$default:
builders:
app_strings|importer_builder:
enabled: true
generate_for:
include:
- lib/CUSTOM_FOLDER/*.dart
app_strings|key_builder:
enabled: true
generate_for:
include:
- lib/CUSTOM_FOLDER/*.dart
app_strings|loader_builder:
enabled: true
generate_for:
include:
- lib/CUSTOM_FOLDER/*.dart
app_strings|json_builder:
enabled: true
generate_for:
include:
- lib/CUSTOM_FOLDER/*.dart
警告: 路径应该对所有构建器相同。
减少构建时间
为了减少构建时间,你可以禁用不需要的构建器。例如,如果你不使用 easy_localization,可以禁用 loader_builder
。
targets:
$default:
builders:
app_strings|importer_builder:
enabled: false
app_strings|key_builder:
enabled: true
app_strings|loader_builder:
enabled: false
app_strings|json_builder:
enabled: true
更多关于Flutter本地化字符串管理插件app_strings的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter本地化字符串管理插件app_strings的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
当然,关于在Flutter中使用app_strings
插件进行本地化字符串管理,以下是一个具体的代码案例来展示如何使用该插件。
安装插件
首先,你需要在你的pubspec.yaml
文件中添加app_strings
依赖:
dependencies:
flutter:
sdk: flutter
app_strings: ^2.0.0 # 请检查最新版本号
然后运行flutter pub get
来安装依赖。
配置本地化资源
在你的项目根目录下创建assets/locales
文件夹,并在其中添加你的本地化资源文件。例如,你可以创建en.json
和zh.json
文件:
assets/locales/en.json
{
"welcome_message": "Welcome to our app!",
"goodbye_message": "Goodbye!"
}
assets/locales/zh.json
{
"welcome_message": "欢迎来到我们的应用!",
"goodbye_message": "再见!"
}
更新pubspec.yaml
确保在pubspec.yaml
中声明这些资源文件:
flutter:
assets:
- assets/locales/en.json
- assets/locales/zh.json
初始化AppStrings
在你的main.dart
文件中,你需要初始化AppStrings
实例并加载相应的本地化资源。
main.dart
import 'package:flutter/material.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:app_strings/app_strings.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
localizationsDelegates: [
// 添加Flutter自带的本地化委托
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
// 添加AppStrings本地化委托
AppStrings.delegate,
],
supportedLocales: [
Locale('en', ''),
Locale('zh', ''),
],
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
late AppStrings appStrings;
@override
void initState() {
super.initState();
// 初始化AppStrings实例
appStrings = AppStrings(
context: context,
// 指定资源文件的路径
assetName: 'assets/locales/',
// 默认语言
defaultLocale: Locale('en'),
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(appStrings.of('welcome_message')),
),
body: Center(
child: ElevatedButton(
onPressed: () {
// 切换语言示例
appStrings.setLocale(Locale('zh'));
setState(() {}); // 强制重新构建UI以更新文本
},
child: Text('Change to Chinese'),
),
),
);
}
}
使用本地化字符串
在上面的代码中,我们已经展示了如何使用appStrings.of('key')
方法来获取本地化字符串。当按钮被点击时,应用的语言会切换到中文,并且UI会重新构建以显示新的本地化字符串。
完整代码结构
确保你的项目结构类似于以下:
your_flutter_app/
├── assets/
│ └── locales/
│ ├── en.json
│ └── zh.json
├── lib/
│ ├── main.dart
├── pubspec.yaml
这样,你就成功地使用app_strings
插件来管理Flutter应用的本地化字符串了。