Flutter国际化插件i18n_json的使用
Flutter国际化插件i18n_json的使用
简介
i18n_json
是一个用于替代 vscode-flutter-i18n-json
插件的 Dart 代码生成器。该项目并不是原始插件的完全替换品,而只是代码生成器的替换,因为原来的代码生成器存在许多错误和缺失的功能。
此项目不是一个 VS Code 插件,而是一个简单的命令行工具,用于将 JSON 文件转换为 Dart 类。
要使用它,请在 pubspec.yaml
中添加以下依赖项:
dev_dependencies:
i18n_json: ^1.0.0
然后通过运行以下命令来生成 i18n.dart
文件:
flutter pub run i18n_json
特性
- 完全兼容 VSCode 插件。
- 自动检测您的项目是否启用了“Sound Null Safety”。
- 能够添加注释(通过 YAML,参见下文)。
- 实验性的性别与复数支持(参见下文)。
注意事项
该 CLI 工具支持 YAML 和 JSON 本地化文件。这是为了允许在您的本地化文件中添加注释,因为 JSON 不支持注释,但 YAML 支持。
要在本地化文件中使用注释,请将文件扩展名更改为 .yaml
,这样该工具可以检测到它。如果同时存在 .yaml
和 .json
文件,.yaml
文件将被加载。
要添加复数或性别,请按如下方式编写:
"sentItems":
{
"__gender":{
"male": {"__plural":
{
"zero": "他发送了你零个{item}",
"one": "他发送了你一个{item}",
"other": "他发送了你{count}个{item}"
}},
"female": {"__plural":
{
"zero": "她发送了你零个{item}",
"one": "她发送了你一个{item}",
"other": "她发送了你{count}个{item}"
}},
"other": {"__plural":
{
"zero": "他们发送了你零个{item}",
"one": "他们发送了你一个{item}",
"other": "他们发送了你{count}个{item}"
}},
},
}
这将生成以下 Dart 代码:
String sentItems(int count, String gender, String item){
if (gender == 'male'){
if (count == 0){
return "他发送了你零个${item}";
} else if (count == 1){
return "他发送了你一个${item}";
} else {
return "他发送了你${count}个${item}";
}
} else if (gender == 'female'){
if (count == 0){
return "她发送了你零个${item}";
} else if (count == 1){
return "她发送了你一个${item}";
} else {
return "她发送了你${count}个${item}";
}
} else {
if (count == 0){
return "他们发送了你零个${item}";
} else if (count == 1){
return "他们发送了你一个${item}";
} else {
return "他们发送了你${count}个${item}";
}
}
}
请注意,“count”变量在复数中自动添加,“gender”变量在性别中自动添加。
完整示例
步骤 1: 添加依赖
在 pubspec.yaml
文件中添加 i18n_json
依赖项:
dev_dependencies:
i18n_json: ^1.0.0
步骤 2: 创建本地化文件
创建一个名为 en.yaml
的文件,并添加以下内容:
sentItems:
__gender:
male:
__plural:
zero: "他发送了你零个{item}"
one: "他发送了你一个{item}"
other: "他发送了你{count}个{item}"
female:
__plural:
zero: "她发送了你零个{item}"
one: "她发送了你一个{item}"
other: "她发送了你{count}个{item}"
other:
__plural:
zero: "他们发送了你零个{item}"
one: "他们发送了你一个{item}"
other: "他们发送了你{count}个{item}"
步骤 3: 生成 Dart 文件
运行以下命令以生成 i18n.dart
文件:
flutter pub run i18n_json
步骤 4: 在应用中使用
在应用中使用生成的 i18n.dart
文件。例如,在 main.dart
中:
import 'package:flutter/material.dart';
import 'package:i18n_json/i18n.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
[@override](/user/override)
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('国际化示例'),
),
body: Center(
child: Text(
I18n.of(context).sentItems(2, 'male', 'message'),
style: TextStyle(fontSize: 20),
),
),
),
);
}
}
更多关于Flutter国际化插件i18n_json的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html
1 回复