根据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”。您忘了添加依赖项吗?
怎么了?
答案 0 :(得分:2)
这是如何设置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
。答案 1 :(得分:0)
您需要跑步
flutter packages get
首先