Flutter JSON配置生成插件json_config_generator的使用
Flutter JSON配置生成插件json_config_generator的使用
1. 整理后的内容中关于“Flutter JSON配置生成插件json_config_generator的使用”的完整示例demo
import 'package:json_config_annotation/json_config_annotation.dart';
import 'dart:convert';
import 'package:flutter/services.dart';
part 'config.g.dart'; //{dart file name}.g.dart
@Configuration(
environmentEnumName: 'Env',
environments:[
Environment(name:'dev', path:'assets/config/dev.json'),
Environment(name:'prd', path:'assets/config/prd.json'),
],
)
class $Config{}
class _CustomClass {
const _CustomClass({required this.value1, required this.value2});
factory _CustomClass.fromJson(Map<String, dynamic> customClass) => _CustomClass(
value1: customClass['value_1'] as String,
value2: customClass['value_2'] as String,
);
final String value1;
final String value2;
}
class _CustomList {
const _CustomList({required this.value1});
factory _CustomList.fromJson(Map<String, dynamic> customList) => _CustomList(
value1: customList['value_1'] as String,
);
final String value1;
static List<_CustomList> listFromJson(List data) => data.map((e) => _CustomList.fromJson(e as Map<String, dynamic>)).toList();
}
enum Env { dev, prd }
class Config {
Config._();
static final instance = Config._();
late String baseUrl;
late _CustomClass customClass;
late int intValue;
late double doubleValue;
late bool booleanValue;
late List<String> stringList;
late List<int> intList;
late List<bool> boolList;
late List<_CustomList> customList;
Future<void> init(Env env) async {
String path = '';
switch (env) {
case Env.dev:
path = 'assets/config/dev.json';
break;
case Env.prd:
path = 'assets/config/prd.json';
break;
}
final jsonString = await rootBundle.loadString(path);
final config = json.decode(jsonString) as Map<String, dynamic>;
baseUrl = config['base_url'] as String;
customClass =
_CustomClass.fromJson(config['custom_class'] as Map<String, dynamic>);
intValue = config['int_value'] as int;
doubleValue = config['double_value'] as double;
booleanValue = config['boolean_value'] as bool;
stringList = (config['string_list'] as List).cast<String>();
intList = (config['int_list'] as List).cast<int>();
boolList = (config['bool_list'] as List).cast<bool>();
customList = _CustomList.listFromJson(config['custom_list'] as List);
}
}
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Config.instance.init(Env.dev);
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter JSON Config Generator',
home: Scaffold(
appBar: AppBar(
title: Text('Flutter JSON Config Generator'),
),
body: Center(
child: Text(
'baseUrl: ${Config.instance.baseUrl}\n'
'customClass.value1: ${Config.instance.customClass.value1}\n'
'intValue: ${Config.instance.intValue}\n'
'doubleValue: ${Config.instance.doubleValue}\n'
'booleanValue: ${Config.instance.booleanValue}\n'
'stringList: ${Config.instance.stringList.join(', ')}\n'
'intList: ${Config.instance.intList.join(', ')}\n'
'boolList: ${Config.instance.boolList.join(', ')}\n'
'customList: ${Config.instance.customList.map((item) => item.value1).join(', ')}',
),
),
),
);
}
}
2. 参考我提供的内容和示例代回答“Flutter JSON配置生成插件json_config_generator的使用”对应的内容
动机
如果你使用JSON文件来配置你的应用程序,也许你需要编写一个包含所有变量及其数据类型的Dart类。当你需要管理嵌套对象时会更加复杂。即使你想在JSON中添加或删除一个值,你也需要修改你的Dart类。
如果你想管理环境,你需要手动为每个需要的环境写入文件路径。
json_config_generator
想要帮助你轻松地处理配置文件和环境的管理。
安装
要使用 json_config_generator
,你需要 build_runner
/code-generator 设置。首先,通过将它们添加到你的 pubspec.yaml
文件中来安装 build_runner
和 json_config_generator
:
dependencies:
json_config_annotation: ^0.1.0
dev_dependencies:
build_runner:
json_config_generator: ^0.1.0
build_runner
是运行代码生成器的工具json_config_generator
是代码生成器json_config_annotation
包含用于json_config_generator
的的注解
如何使用
要使用此生成器,需要创建一个空的配置Dart类,该类以 $
开头,并使用 Configuration
注解定义你想要拥有的环境。每个环境都有 name
和 path
,如果有多个,则生成一个 Enum
来表示环境。你还可以指定这个 Enum
的名称,默认名称是 Environment
。此外,还需要添加一些导入。
import 'package:json_config_annotation/json_config_annotation.dart';
import 'dart:convert';
import 'package:flutter/services.dart';
part 'config.g.dart'; //{dart file name}.g.dart
@Configuration(
environmentEnumName: 'Env',
environments:[
Environment(name:'dev', path:'assets/config/dev.json'),
Environment(name:'prd', path:'assets/config/prd.json'),
],
)
class $Config{}
假设你有以下JSON文件:
{
"base_url": "https://example.com",
"custom_class": {
"value_1": "dfgdfgdfgwqrrqwrqweqwe324523b252dghfdhd",
"value_2": "6Lez7aIaAAAAAN6qZG234c25bv666b7yn5m8m6"
},
"int_value": 3,
"double_value": 3.5,
"boolean_value": true,
"string_list": ["hello", "world"],
"int_list": [1, 23, 5],
"bool_list": [false, true, true],
"custom_list": [
{
"value_1": "hello"
},
{
"value_1": "world"
}
]
}
生成器会创建:
enum Env { dev, prd }
class Config {
Config._();
static final instance = Config._();
late String baseUrl;
late _CustomClass customClass;
late int intValue;
late double doubleValue;
late bool booleanValue;
late List<String> stringList;
late List<int> intList;
late List<bool> boolList;
late List<_CustomList> customList;
Future<void> init(Env env) async {
String path = '';
switch (env) {
case Env.dev:
path = 'assets/config/dev.json';
break;
case Env.prd:
path = 'assets/config/prd.json';
break;
}
final jsonString = await rootBundle.loadString(path);
final config = json.decode(jsonString) as Map<String, dynamic>;
baseUrl = config['base_url'] as String;
customClass =
_CustomClass.fromJson(config['custom_class'] as Map<String, dynamic>);
intValue = config['int_value'] as int;
doubleValue = config['double_value'] as double;
booleanValue = config['boolean_value'] as bool;
stringList = (config['string_list'] as List).cast<String>();
intList = (config['int_list'] as List).cast<int>();
boolList = (config['bool_list'] as List).cast<bool>();
customList = _CustomList.listFromJson(config['custom_list'] as List);
}
}
class _CustomClass {
const _CustomClass({required this.value1, required this.value2});
factory _CustomClass.fromJson(Map<String, dynamic> customClass) => _CustomClass(
value1: customClass['value_1'] as String,
value2: customClass['value_2'] as String,
);
final String value1;
final String value2;
}
class _CustomList {
const _CustomList({required this.value1});
factory _CustomList.fromJson(Map<String, dynamic> customList) => _CustomList(
value1: customList['value_1'] as String,
);
final String value1;
static List<_CustomList> listFromJson(List data) => data.map((e) => _CustomList.fromJson(e as Map<String, dynamic>)).toList();
}
更多关于Flutter JSON配置生成插件json_config_generator的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter JSON配置生成插件json_config_generator的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
当然,以下是关于如何在Flutter项目中使用json_config_generator
插件的一个详细示例。这个插件可以帮助你从JSON配置文件生成Dart类,便于在Flutter项目中轻松处理JSON数据。
步骤1:添加依赖
首先,你需要在pubspec.yaml
文件中添加json_config_generator
依赖:
dependencies:
flutter:
sdk: flutter
json_config_generator: ^最新版本号 # 请替换为实际的最新版本号
dev_dependencies:
build_runner: ^最新版本号 # json_config_generator 需要使用 build_runner 来生成代码
步骤2:创建JSON配置文件
在你的项目根目录下创建一个名为config.json
的文件,内容如下:
{
"app_name": "My Flutter App",
"api_url": "https://api.example.com",
"theme": {
"primary_color": "#FF5733",
"background_color": "#FFFFFF"
}
}
步骤3:生成Dart类
在项目根目录下打开终端,运行以下命令来生成Dart类:
flutter pub get
flutter pub run build_runner build --delete-conflicting-outputs
假设你使用的是默认配置,json_config_generator
会在项目根目录下生成一个config.g.dart
文件,里面包含了与config.json
对应的Dart类。
步骤4:使用生成的Dart类
现在你可以在Flutter项目的代码中使用生成的Dart类来加载和处理JSON配置了。
首先,确保你已经导入了生成的Dart文件:
import 'config.g.dart';
然后,你可以像这样加载和使用配置:
import 'dart:convert';
import 'package:flutter/material.dart';
import 'config.g.dart'; // 导入生成的Dart文件
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
// 假设你的JSON配置文件是一个字符串
String jsonConfig = '''
{
"app_name": "My Flutter App",
"api_url": "https://api.example.com",
"theme": {
"primary_color": "#FF5733",
"background_color": "#FFFFFF"
}
}
''';
// 解析JSON字符串为Dart对象
final Config config = Config.fromJson(jsonDecode(jsonConfig));
return MaterialApp(
title: config.appName,
theme: ThemeData(
primarySwatch: Color(int.parse(config.theme.primaryColor.substring(1), 16)),
backgroundColor: Color(int.parse(config.theme.backgroundColor.substring(1), 16)),
),
home: Scaffold(
appBar: AppBar(
title: Text(config.appName),
),
body: Center(
child: Text('API URL: ${config.apiUrl}'),
),
),
);
}
}
注意事项
- 配置文件路径:默认情况下,
json_config_generator
会查找项目根目录下的config.json
文件。如果你需要指定其他文件,请查阅插件的文档进行配置。 - JSON格式:确保你的JSON文件是有效的,否则在生成Dart类时会报错。
- 颜色解析:在上面的示例中,颜色值是从十六进制字符串解析为
Color
对象的。你需要确保颜色字符串的格式是正确的(即以#
开头)。
通过上述步骤,你应该能够在Flutter项目中成功使用json_config_generator
插件来生成和使用JSON配置。