}
我们在这里使用了dart语法糖创建了构造函数。具体请参考(www.dartlang.org/guides/lang…)。
第四步:关联实体类文件
我们需要在我们的实体类中关联生成文件。
import ‘package:json_annotation/json_annotation.dart’;
part ‘data.g.dart’;
@JsonSerializable()
class Data {
final String by;
final int descendants;
final int id;
final List kids;
final int score;
final int time;
final String title;
final String type;
@JsonKey(nullable: false)
final String url;
Data({this.by, this.descendants, this.id, this.kids, this.score, this.time,
this.title, this.type, this.url});
刚写完data.g.dart的会报错,这是正常的!因为我们还没生成解析文件
- 为了使实体类文件找到生成文件,我们需要 part ‘data.g.dart’。
第五步:生成Json解析文件
当当当…!这里开始就是重头戏了!!
我们要使用JsonSerializable生成代码的话必须要在需要生成代码的实体类前添加注解@JsonSerializable(),而要使用这个注解我们必须引入json_annotation/json_annotation.dart这个包。
import ‘package:json_annotation/json_annotation.dart’;
@JsonSerializable()
class Data{
final String by;
final int descendants;
final int id;
final List kids;
final int score;
final int time;
final String title;
final String type;
final String url;
Data({this.by, this.descendants, this.id, this.kids, this.score, this.time,
this.title, this.type, this.url});
}
这里需要注意,flutter编码规范dart文件名统一小写,这样可以避免很多问题。ok这样实体类就创建完成啦。
那么问题来了,应该如何生成代码呢?
还记得我们刚才添加的build_runner的依赖吗,这时候我们就需要它来帮忙咯。
build_runner
build_runner是dart团队提供的一个生成dart代码文件的外部包。
我们在当前项目的目录下运行flutter packages pub run build_runner build
<