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

问题描述 投票:0回答:2

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

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

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);
}

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);
}

运行命令

flutter pub run build_runner build
运行时没有任何错误,并且所有红色波浪线消失。

3.尝试反序列化

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

const String stringResponse = '{"Status": "Success", "Response": { "firstName": "XYZ", "middleName": "ABC", "surname": "EDF", "username": "abc", "emailId": "[email protected]" } }';

final Map<String, dynamic> encoded = jsonDecode(stringResponse);
final ResponseWrapper<NewUser> newUserWithWrapper = ResponseWrapper.fromJson(encoded, NewUser.fromJson);

在上面的代码块中,在最后一行的

NewUser.fromJson
我收到红色波浪线错误,内容如下:
The argument type 'NewUser Function(Map<String, dynamic>)' can't be assigned to the parameter type 'NewUser Function(Object?)'.

flutter dart generics freezed flutter-freezed
2个回答
7
投票

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

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

0
投票
© www.soinside.com 2019 - 2024. All rights reserved.