Flutter如何使用json_serializable_generator
在Flutter项目中配置json_serializable_generator时遇到问题,按照官方文档添加依赖后运行flutter pub run build_runner build命令,但始终无法生成对应的.g.dart文件。控制台报错提示"Could not find package:build_runner",但build_runner明明已添加到dev_dependencies中。请问正确的配置步骤是什么?是否需要额外设置build.yaml文件?
2 回复
使用json_serializable_generator的步骤:
- 添加依赖:
dependencies:
json_annotation: ^4.8.1
dev_dependencies:
json_serializable: ^6.7.1
build_runner: ^2.4.4
- 创建模型类:
import 'package:json_annotation/json_annotation.dart';
part 'user.g.dart';
@JsonSerializable()
class User {
final String name;
final int age;
User({required this.name, required this.age});
factory User.fromJson(Map<String, dynamic> json) => _$UserFromJson(json);
Map<String, dynamic> toJson() => _$UserToJson(this);
}
- 生成代码: 在终端运行:
flutter pub run build_runner build
- 使用:
// 从JSON创建对象
var user = User.fromJson(json.decode(jsonString));
// 转换为JSON
String jsonStr = json.encode(user.toJson());
注意:修改模型后需要重新运行build命令。
更多关于Flutter如何使用json_serializable_generator的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
在Flutter中使用json_serializable_generator,可以自动生成JSON序列化代码,简化数据模型处理。以下是步骤:
-
添加依赖
在pubspec.yaml中:dependencies: json_annotation: ^4.8.1 dev_dependencies: json_serializable: ^6.7.1 build_runner: ^2.4.4 -
创建数据模型
例如user.dart:import 'package:json_annotation/json_annotation.dart'; part 'user.g.dart'; [@JsonSerializable](/user/JsonSerializable)() class User { final String name; final int age; User({required this.name, required this.age}); factory User.fromJson(Map<String, dynamic> json) => _$UserFromJson(json); Map<String, dynamic> toJson() => _$UserToJson(this); } -
生成代码
运行命令(在项目根目录):flutter pub run build_runner build这会生成
user.g.dart文件,包含_$UserFromJson和_$UserToJson方法。 -
使用示例
// JSON转对象 Map<String, dynamic> json = {'name': 'Alice', 'age': 25}; User user = User.fromJson(json); // 对象转JSON Map<String, dynamic> userJson = user.toJson();
注意:
- 修改模型后需重新运行生成命令。
- 使用
build_runner watch可自动监听文件变化并重新生成。 - 字段命名需与JSON键匹配,或用
@JsonKey(name: 'json_name')指定映射。
此方法减少手动编码错误,提高开发效率。

