Home > Software design >  Unable to generate fromJson() and toJson() for generics using freezed package
Unable to generate fromJson() and toJson() for generics using freezed package

Time:03-09

We are trying to create a generic Category class. At the time being, we are unsure whether category will have integer or UUID as key. Hence, we need the id to be generic for now. All works fine. However, we are unable to generate the fromJson() and toJson() using the freezed package.

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

Error:

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

As the error message suggests, I have used the @JsonSerializable(genericArgumentFactories: true) annotation however, it is not working as suggested. How can I get the fromJson() and toJson() methods with freezed for generics?

CodePudding user response:

Unsupported feature at the moment.

Source: Issue #616

  • Related