flutter如何生成model
在Flutter开发中,如何快速生成数据模型类(model)?有没有推荐的代码生成工具或插件?手动编写model效率太低,特别是处理JSON序列化时很麻烦。像json_serializable这类工具具体要怎么配置和使用?最好能给出一个完整的示例,包括依赖配置和生成命令的步骤。
2 回复
使用 json_serializable 包,步骤如下:
- 在
pubspec.yaml添加依赖:json_annotation和json_serializable。 - 创建模型类,使用
@JsonSerializable()注解。 - 运行
flutter pub run build_runner build生成.g.dart文件。
更多关于flutter如何生成model的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
在 Flutter 中生成 Model 类有多种方式,以下是常用的方法:
1. 手动创建 Model 类
class User {
final int id;
final String name;
final String email;
User({
required this.id,
required this.name,
required this.email,
});
factory User.fromJson(Map<String, dynamic> json) {
return User(
id: json['id'],
name: json['name'],
email: json['email'],
);
}
Map<String, dynamic> toJson() {
return {
'id': id,
'name': name,
'email': email,
};
}
}
2. 使用 json_serializable(推荐)
步骤:
- 添加依赖到
pubspec.yaml:
dependencies:
json_annotation: ^4.8.1
dev_dependencies:
json_serializable: ^6.7.1
build_runner: ^2.4.6
- 创建 Model 类:
import 'package:json_annotation/json_annotation.dart';
part 'user.g.dart';
@JsonSerializable()
class User {
final int id;
final String name;
final String email;
User({
required this.id,
required this.name,
required this.email,
});
factory User.fromJson(Map<String, dynamic> json) => _$UserFromJson(json);
Map<String, dynamic> toJson() => _$UserToJson(this);
}
- 生成代码:
flutter pub run build_runner build
3. 使用在线工具
可以使用 QuickType 或 JSON to Dart 等在线工具,粘贴 JSON 数据自动生成 Model 类。
4. IDE 插件
- Flutter Data Class(Android Studio/IntelliJ)
- JSON to Dart Model(VS Code)
推荐使用 json_serializable,因为它提供类型安全、自动生成代码,并且易于维护。

