我们正在尝试创建一个通用的 Category 类。目前,我们不确定类别是否以整数或 UUID 作为键。因此,我们现在需要 id 是通用的。一切正常。但是,我们无法使用
freezed
包生成 fromJson() 和 toJson()。
import 'package:freezed_annotation/freezed_annotation.dart';
part 'category.freezed.dart';
part 'category.g.dart';
@freezed
@JsonSerializable(genericArgumentFactories: true)
class Category<T> with _$Category<T> {
factory Category({
required T id,
required String name,
required String imageUrl,
}) = _Category;
factory Category.fromJson(Map<String, dynamic> json) =>
_$CategoryFromJson(json);
}
错误:
Could not generate `fromJson` code for `id` because of type `T` (type parameter).
To support type parameters (generic types) you can:
* Use `JsonConverter`
https://pub.dev/documentation/json_annotation/latest/json_annotation/JsonConverter-class.html
* Use `JsonKey` fields `fromJson` and `toJson`
https://pub.dev/documentation/json_annotation/latest/json_annotation/JsonKey/fromJson.html
https://pub.dev/documentation/json_annotation/latest/json_annotation/JsonKey/toJson.html
* Set `JsonSerializable.genericArgumentFactories` to `true`
https://pub.dev/documentation/json_annotation/latest/json_annotation/JsonSerializable/genericArgumentFactories.html
package:mobile/data/models/category.freezed.dart:144:11
╷
144 │ final T id;
│ ^^
╵
[SEVERE] Failed after 2.4s
pub finished with exit code 1
正如错误消息所示,我使用了
@JsonSerializable(genericArgumentFactories: true)
注释,但是它没有按建议工作。如何获得泛型冻结的 fromJson()
和 toJson()
方法?
目前不支持的功能。
来源:问题#616
如果我没记错的话,它已经被支持了: https://pub.dev/packages/freezed#deserializing-generic-classes
您在代码中唯一需要调整的是
fromJson
函数:
factory Category.fromJson(Map<String, dynamic> json, T Function(Object?) fromJsonT) => _$CategoryFromJson(json, fromJsonT);
已使用
@JsonSerializable(genericArgumentFactories: true)
修复
根据文档:
当
true
在具有类型参数(泛型类型)的类上时,额外
将为 fromJson
和/或 toJson
生成“helper”参数
支持序列化这些类型的值。
例如,生成的代码
@JsonSerializable(genericArgumentFactories: true)
class Response<T> {
int status;
T value;
}
看起来像
Response<T> _$ResponseFromJson<T>(
Map<String, dynamic> json,
T Function(Object json) fromJsonT,
) {
return Response<T>()
..status = json['status'] as int
..value = fromJsonT(json['value']);
}
Map<String, dynamic> _$ResponseToJson<T>(
Response<T> instance,
Object Function(T value) toJsonT,
) =>
<String, dynamic>{
'status': instance.status,
'value': toJsonT(instance.value),
};
备注:
build.yaml
为包中的所有类设置了此选项
它仅适用于具有类型参数的类 - 因此不会出现警告
呼应。