0

我们正在尝试创建一个通用的 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()

4

0 回答 0