我正在使用json_serializable
,json_annotation
,并进行构建以为我的模型生成serialization/deserialization
功能。但是,当我运行构建时,出现此错误。
运行JsonSerializableGenerator时出错无法填充所需的构造函数参数:已创建。package:explorer / models / Account / account.dart:46:3
它所指的行是我的模型构造函数。
Account(String id, String firstName, String lastName, String email,
DateTime dob, DateTime created, DateTime updated,
{String accessTkn, String refreshTkn}) {}
为什么会出现此错误?
根据要求,这是我的模型课。
import "package:json_annotation/json_annotation.dart";
part "account.g.dart";
@JsonSerializable(nullable: true)
class Account {
@JsonKey(name: "id")
String _id;
@JsonKey(name: "first_name")
String _firstName;
@JsonKey(name: "last_name")
String _lastName;
@JsonKey(name: "email")
String _email;
@JsonKey(
name: "dob", fromJson: _isoStringToDateTime, toJson: _dateTimeToIsoString)
DateTime _dob;
@JsonKey(
name: "created",
fromJson: _isoStringToDateTime,
toJson: _dateTimeToIsoString)
DateTime _created;
@JsonKey(
name: "updated",
fromJson: _isoStringToDateTime,
toJson: _dateTimeToIsoString)
DateTime _updated;
@JsonKey(name: "access_token")
String _accessToken;
@JsonKey(name: "refresh_token")
String _refreshToken;
Account(String id, String firstName, String lastName, String email,
DateTime dob, DateTime created, DateTime updated,
{String accessTkn, String refreshTkn}) {
this._id = id;
this._firstName = firstName;
this._lastName = lastName;
this._email = email;
this._dob = dob;
this._created = created;
this._updated = updated;
this._accessToken = accessToken;
this._refreshToken = refreshTkn;
}
factory Account.fromJson(Map<String, dynamic> json) {
_$AccountFromJson(json);
}
// converts a DateTime to a ISO string
static String _dateTimeToIsoString(DateTime date) {
return date.toIso8601String();
}
// convert back to date time
static DateTime _isoStringToDateTime(String iso) {
return DateTime.parse(iso);
}
/// get the account id
String get id {
return this._id;
}
/// get the account first name
String get firstName {
return this._firstName;
}
/// get the account last name
String get lastName {
return this._lastName;
}
/// get the account email.
String get email {
return this._email;
}
/// get the account owner's date of birth
DateTime get dob {
return this._dob;
}
/// Get the date the account was created.
DateTime get createdAt {
return this._created;
}
/// get teh date the account was last updated.
DateTime get updatedAt {
return this._updated;
}
// get the account access token.
String get accessToken {
return this._accessToken;
}
// get the account refresh token.
String get refreshToken {
return this._refreshToken;
}
/// clones the account instance
Account clone() {
return Account(this.id, this.firstName, this.lastName, this.email, this.dob,
this.createdAt, this.updatedAt,
accessTkn: this.accessToken, refreshTkn: this.refreshToken);
}
Map<String, dynamic> toJson() {
_$AccountToJson(this);
}
}
由于没有初始化传递的参数,所以有一个空的构造函数,所以出现错误。
您必须初始化类中具有的每个参数,或使用JsonSerializable(nullable: true)
或JsonKey(nullable: true)
允许它们为空>
如果该解决方案不适合您,请共享您班上的所有代码