无法使用冻结包为泛型生成 fromJson() 和 toJson()

Ari*_*iel 5 generics dart flutter json-serializable freezed

我们正在尝试创建一个通用的 Category 类。目前,我们不确定类别是否以整数或 UUID 作为键。因此,我们现在需要 id 是通用的。一切正常。但是,我们无法使用该freezed包生成 fromJson() 和 toJson()。

\n
import \'package:freezed_annotation/freezed_annotation.dart\';\n\npart \'category.freezed.dart\';\npart \'category.g.dart\';\n\n@freezed\n@JsonSerializable(genericArgumentFactories: true)\nclass Category<T> with _$Category<T> {\n  factory Category({\n    required T id,\n    required String name,\n    required String imageUrl,\n  }) = _Category;\n\n  factory Category.fromJson(Map<String, dynamic> json) =>\n      _$CategoryFromJson(json);\n}\n
Run Code Online (Sandbox Code Playgroud)\n

错误:

\n
Could not generate `fromJson` code for `id` because of type `T` (type parameter).\nTo support type parameters (generic types) you can:\n* Use `JsonConverter`\n  https://pub.dev/documentation/json_annotation/latest/json_annotation/JsonConverter-class.html\n* Use `JsonKey` fields `fromJson` and `toJson`\n  https://pub.dev/documentation/json_annotation/latest/json_annotation/JsonKey/fromJson.html\n  https://pub.dev/documentation/json_annotation/latest/json_annotation/JsonKey/toJson.html\n* Set `JsonSerializable.genericArgumentFactories` to `true`\n  https://pub.dev/documentation/json_annotation/latest/json_annotation/JsonSerializable/genericArgumentFactories.html\npackage:mobile/data/models/category.freezed.dart:144:11\n    \xe2\x95\xb7\n144 \xe2\x94\x82   final T id;\n    \xe2\x94\x82           ^^\n    \xe2\x95\xb5\n[SEVERE] Failed after 2.4s\npub finished with exit code 1\n\n
Run Code Online (Sandbox Code Playgroud)\n

正如错误消息所示,我已经使用了@JsonSerializable(genericArgumentFactories: true)注释,但是它没有按建议工作。如何获得泛型冻结的fromJson()和方法?toJson()

\n

Ari*_*iel 4

目前不支持的功能。

来源:问题 #616