根据json_serializable包installing instructions,您应该添加以下依赖项:
dependencies:
json_serializable: ^2.0.3
这是我的代码:
import 'package:json_annotation/json_annotation.dart';
part 'person.g.dart';
@JsonSerializable(nullable: false)
class Person {
final String firstName;
final String lastName;
final DateTime dateOfBirth;
Person({this.firstName, this.lastName, this.dateOfBirth});
factory Person.fromJson(Map<String, dynamic> json) => _$PersonFromJson(json);
Map<String, dynamic> toJson() => _$PersonToJson(this);
}
现在在Flutter中运行:
flutter packages pub run build_runner build
或者对于Dart项目:
pub run build_runner build
我收到以下错误:
找不到包“build_runner”。你忘了添加一个依赖吗?
怎么了?
这是如何设置Pub以自动生成安装说明的问题。以下是您实际需要添加的依赖项:
dependencies:
json_annotation: ^2.0.0
dev_dependencies:
build_runner: ^1.0.0
json_serializable: ^2.0.0
这显示在json_serializable
example中。
现在您可以为这样的类生成dart文件
import 'package:json_annotation/json_annotation.dart';
part 'person.g.dart';
@JsonSerializable(nullable: false)
class Person {
final String firstName;
final String lastName;
final DateTime dateOfBirth;
Person({this.firstName, this.lastName, this.dateOfBirth});
factory Person.fromJson(Map<String, dynamic> json) => _$PersonFromJson(json);
Map<String, dynamic> toJson() => _$PersonToJson(this);
}
通过在Flutter项目中运行它:
flutter packages pub run build_runner build
或者在Dart项目中:
pub run build_runner build
part 'person.g.dart'
与person.dart
模型类文件的名称相匹配。也就是说,不要称之为example.g.dart
。你需要先运行flutter packages get