如何动态地将T.fromJson()传递给Flutter类< T>?

cbwuti44  于 2023-03-13  发布在  Flutter
关注(0)|答案(1)|浏览(151)

我正在处理Flutter项目的ApiResponse类,这个类需要一个T data属性。
我想使用JsonSerializable来生成fromJson()方法,但当我尝试执行以下操作时出现此错误:

ListResponse<T> _$ListResponseFromJson<T extends JsonSerializable>(Map<String, dynamic> json, T Function(Object?) fromJsonT)

我定义了这两个文件:
1.基础响应

part "base_response.g.dart";

@JsonSerializable()
abstract class BaseResponse {
  dynamic message;
  bool success;

  BaseResponse({this.message, required this.success});

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

2.列表响应

part "list_response.g.dart";

@JsonSerializable(genericArgumentFactories: true)
class ListResponse<T extends JsonSerializable> extends BaseResponse {
  List<T> data;

  ListResponse({
    required String super.message,
    required super.success,
    required this.data,
  });

  factory ListResponse.fromJson(Map<String, dynamic> json) =>
      _$ListResponseFromJson(json, WHAT SHOULD BE HERE ?);
}

所以我现在的问题是JsonSerializable需要ListResponseFromJson()中的另一个参数:
如何将T.从Json()动态传递到_$ListResponseFromJson(json, ???)

xggvc2p6

xggvc2p61#

您可以使用泛型函数,该函数接受Object?并返回T,然后将其传递给_$ListResponseFromJson方法:

@JsonSerializable(genericArgumentFactories: true)
class ListResponse<T extends JsonSerializable> extends BaseResponse {
  List<T> data;

  ListResponse({
    required String message,
    required bool success,
    required this.data,
  }) : super(message: message, success: success);

  factory ListResponse.fromJson(
      Map<String, dynamic> json, T Function(Object? json) fromJsonT) {
    return _$ListResponseFromJson(json, fromJsonT);
  }

  static T _fromJson<T extends JsonSerializable>(
      Object? json, T Function(Object? json) fromJsonT) {
    return fromJsonT(json);
  }

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

  factory ListResponse.fromList(List<T> list,
      {String message = '', bool success = true}) {
    return ListResponse(
        message: message, success: success, data: List<T>.from(list));
  }

  factory ListResponse.empty({String message = '', bool success = true}) {
    return ListResponse(message: message, success: success, data: []);
  }
}

相关问题