使用带有通用类型类的 Freezed 进行反序列化

Mic*_*thi 3 generics dart flutter freezed flutter-freezed

几个月前引入的反序列化通用类功能被冻结。

我正在尝试遵循文档,但遇到编译时错误:

The argument type 'NameOfClass Function(Map<String, dynamic>)' can't be assigned to the parameter type 'NameOfClass Function(Object?)'.

这是我的数据类的简化版本,用于解释我想要实现的目标。

1. 外部类

@Freezed(genericArgumentFactories: true)
class ResponseWrapper<T> with _$ResponseWrapper<T>{
  const factory ResponseWrapper ({
    final String? Status,
    final T? Response,
  }) = _ResponseWrapper;

  factory ResponseWrapper.fromJson(Map<String, dynamic> json,
      T Function(Object? json) fromJsonT)
    => _$ResponseWrapperFromJson<T>(json, fromJsonT);
}
Run Code Online (Sandbox Code Playgroud)

2. 内部类

@freezed
class NewUser with _$NewUser {
  const factory NewUser({
    String? firstName,
    String? middleName,
    String? surname,
    String? username,
    String? emailId,
  }) = _NewUser;

  factory NewUser.fromJson(Map<String, dynamic> json) =>
      _$NewUserFromJson(json);
}
Run Code Online (Sandbox Code Playgroud)

运行该命令flutter pub run build_runner build不会出现任何错误,并且所有红色波浪线都会消失。

3.尝试反序列化

我使用以下代码来反序列化 json。

const String stringResponse = '{"Status": "Success", "Response": { "firstName": "XYZ", "middleName": "ABC", "surname": "EDF", "username": "abc", "emailId": "abc@gmail.com" } }';

final Map<String, dynamic> encoded = jsonDecode(stringResponse);
final ResponseWrapper<NewUser> newUserWithWrapper = ResponseWrapper.fromJson(encoded, NewUser.fromJson);
Run Code Online (Sandbox Code Playgroud)

在上面的代码块中,在最后一行NewUser.fromJson我收到红色波浪线错误,内容如下: The argument type 'NewUser Function(Map<String, dynamic>)' can't be assigned to the parameter type 'NewUser Function(Object?)'.

Mic*_*thi 5

虽然我不确定这是否是更好的方法,但将最后一行更改为以下内容可以解决问题:

final ResponseWrapper<NewUser> newUserWithWrapper = ResponseWrapper.fromJson(
      encoded,
      (Object? json) => NewUser.fromJson(json as Map<String, dynamic>));
Run Code Online (Sandbox Code Playgroud)