一个生成工具,可以构建一个类,以便从Dart代码中获取您的JSON本地化路径。
入门
- 在您的
pubspec.yaml中添加依赖项
dev_dependencies:
json_locale_generator: ^0.0.3
build_runner: ^2.0.4
- 在您的
pubspec.yaml中配置要为其生成代码的JSON文件
json_to_dart:
sample_files:
# The file assets/en.json will be converted to dart code and values can be accessed via the Locale class
- source: assets/en.json
class_name: Locale
- source: assets/other.json
class_name: Other
- 执行
[dart|flutter] pub run build_runner build或[dart|flutter] pub run json_locale_generator:generate以仅运行json_locale_generator,而不运行其他可能的构建器包。文件jsons.dart将被生成到lib/jsons.dart中 - 导入
jsons.dart并开始使用它
import 'jsons.dart';
FlutterI18n.translate(context, Locale.core.app_title);
特点
将JSON转换为
{
"ok": "OK",
"core": {
"app_name": "WordSing Battle"
},
"home": {
"title": "No card in the deck"
}
}
转换为Dart代码,以便轻松访问每个路径。对于上面的例子,执行GeneratedClass.core.app_name将返回字符串'core.app_name'