Flutter JSON序列化-不生成* .g.dart文件 [英] Flutter JSON Serialization - Not generating *.g.dart files
问题描述
我是扑朔迷离的新手,目标是序列化包含其他较小对象的复杂JSON对象.
I am new to flutter and the objective is to serialise complex JSON objects which contain other smaller objects.
使用json_serializable: ^2.0.0
和pubspec.yaml
文件看起来像这样.
Using the json_serializable: ^2.0.0
and the pubspec.yaml
file looks something like this.
dependencies:
intl: ^0.15.7
json_annotation: ^2.0.0
built_value: ^6.7.1
flutter:
sdk: flutter
dev_dependencies:
build_runner: ^1.0.0
json_serializable: ^2.0.0
built_value_generator: ^6.7.1
flutter_test:
sdk: flutter
user.dart
看起来像这样
import 'package:json_annotation/json_annotation.dart';
part 'user.g.dart';
@JsonSerializable(nullable: false)
class User {
final String firstName;
final String lastName;
final DateTime dateOfBirth;
User({this.firstName, this.lastName, this.dateOfBirth});
factory User.fromJson(Map<String, dynamic> json) => _$UserFromJson(json);
Map<String, dynamic> toJson() => _$UserToJson(this);
}
我已经尝试过flutter pub run build_runner build
,但没有创建user.g.dart文件,而我正面临与此相关的问题.
I have tried flutter pub run build_runner build
yet the file user.g.dart doesn't get created and I am facing issue with that.
我还用以下代码添加了build.yaml
文件
I also have added the build.yaml
file with following code
targets:
$default:
builders:
built_value_generator|built_value:
generate_for:
- model/*.dart
json_serializable|json_serializable:
generate_for:
- model/*.dart
任何人都可以让我知道我在这里想念的是什么.谢谢
Can anyone let me know what I am missing here. Thanks
推荐答案
构造函数的参数不应为可选
The constructor's argument shouldn't be optional
User({this.firstName, this.lastName, this.dateOfBirth});
它们应该是强制性的:
User(this.firstName, this.lastName, this.dateOfBirth);
还有部分
'user.g.dart';
应该匹配大写用户类:
part 'User.g.dart';
这篇关于Flutter JSON序列化-不生成* .g.dart文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!