第一步:新建一个实体
import 'package:json_annotation/json_annotation.dart';
part 'test.g.dart';
@JsonSerializable() //注解
class Author {
String name;
String title;
int id;
Author({this.name, this.title, this.id});
factory Author.fromJson(Map<String, dynamic> json) => _$AuthorFromJson(json);
Map<String, dynamic> toJson(Author instance) => _$AuthorToJson(instance);
}
注意:
1.实体中fromJson和toJson是固定写法,报错提示先忽略
2.part ‘test.g.dart’; 会有报错提示,可以忽略
第二步,pubspec.yml引入依赖
dependencies:
flutter:
sdk: flutter
cupertino_icons: ^1.0.2
json_annotation: ^3.1.1
build_runner: ^1.1.3
json_serializable: ^3.5.1
第三步,在项目根目录下,通过在terminal内输入下面代码,自动生成.g.dart文件
生成.g.dart文件
flutter packages pub run build_runner build
报错可以尝试
flutter packages pub run build_runner build --delete-conflicting-outputs
如果还不行就清理之前生成文件然后在从新生成
flutter packages pub run build_runner clean
flutter packages pub run build_runner build
第四步,遇到问题 Missing “part ‘xxx.g.dart’;”
保证实体类的dart文件名和part ‘test.g.dart’;保持一致