带有继承 class 的 flutter dart JsonSerializable

flutter dart JsonSerializable with inherited class

我有以下两个 classes,其中一个像这样从另一个延伸:

@JsonSerializable(nullable: true)
class Response {
  final String responseCode;
  final String responseMessage;
  final String errorLog;
  Response({this.errorLog, this.responseCode, this.responseMessage});
  factory Response.fromJson(Map<String, dynamic> json) =>
      _$ResponseFromJson(json);
}

................................................ ......

 @JsonSerializable(nullable: false)
class Verify extends Response {
  Data data;
  Verify({
    this.data,
  });
  factory Verify.fromJson(Map<String, dynamic> json) => _$VerifyFromJson(json);
  Map<String, dynamic> toJson() => _$VerifyToJson(this);
}

每当我尝试从 Verify class 读取 response class 属性时,它总是空的。

请问如何实现?

这个我已经通过将参数传递给 super in verify class constructor like this

解决了
@JsonSerializable()
class VerifyResponse extends Response {
  Data data;

  VerifyResponse({
    this.data,
    String responseCode,
    String responseMessage,
  }) : super(responseCode: responseCode, responseMessage: responseMessage);

  factory VerifyResponse.fromJson(Map<String, dynamic> json) =>
      _$VerifyResponseFromJson(json);

  Map<String, dynamic> toJson() => _$VerifyResponseToJson(this);
}

对于响应class,它保持不变

@JsonSerializable()
class Response {
  final String responseCode;
  final String responseMessage;

  Response({this.responseCode, this.responseMessage});

  factory Response.fromJson(Map<String, dynamic> json) =>
      _$ResponseFromJson(json);
}

有点烦人,但就是这样。

您应该从响应中删除 'final' 关键字 Class

@JsonSerializable(nullable: true)
    class Response {
      String responseCode;
      String responseMessage;
      String errorLog;
      Response({this.errorLog, this.responseCode, this.responseMessage});
      factory Response.fromJson(Map<String, dynamic> json) =>
           _$ResponseFromJson(json);
}

它通过将 super(); 显式添加到子 class 的构造函数来工作。

@JsonSerializable()
class VerifyResponse extends Response {
  Data data;

  VerifyResponse({
    this.data,
    String responseCode,
    String responseMessage,
    //No need to list all parent class properties
    }) : super();

  factory VerifyResponse.fromJson(Map<String, dynamic> json) =>
      _$VerifyResponseFromJson(json);

  Map<String, dynamic> toJson() => _$VerifyResponseToJson(this);
}