freezed icon indicating copy to clipboard operation
freezed copied to clipboard

Generic arguments with JsonSerializable

Open AlexanderFarkas opened this issue 1 year ago • 2 comments

This doesn't work:

import 'package:freezed_annotation/freezed_annotation.dart';
part 'data.freezed.dart';
part 'data.g.dart';

@freezed
@JsonSerializable(genericArgumentFactories: true, createToJson: false)
class Data<T> with _$Data<T> {
  const factory Data({
    required T data,
  }) = _Data<T>;

  factory Data.fromJson(
    Map<String, dynamic> json,
    T Function(Object? json) fromJson,
  ) => _$DataFromJson<T>(json, fromJson);
}

Error:

[SEVERE] json_serializable on lib/dummy/models/data.dart:

Could not generate `fromJson` code for `data` 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
   ╷
96 │   final T data;
   │           ^^^^
   ╵

If I change above to (just replace arrow function with body):

import 'package:freezed_annotation/freezed_annotation.dart';
part 'data.freezed.dart';
part 'data.g.dart';

@freezed
@JsonSerializable(genericArgumentFactories: true, createToJson: false)
class Data<T> with _$Data<T> {
  const factory Data({
    required T data,
  }) = _Data<T>;

  factory Data.fromJson(
    Map<String, dynamic> json,
    T Function(Object? json) fromJson,
  ) {
    return _$DataFromJson<T>(json, fromJson);
  } 
}

It builds without any errors.

ENV:

deps: 
freezed_annotation: ^2.1.0
json_annotation: ^4.7.0

dev deps:
freezed: ^2.1.1
json_serializable: ^6.4.1
build_runner: ^2.2.1

build.yaml is not defined

AlexanderFarkas avatar Oct 07 '22 17:10 AlexanderFarkas

I'm having the same issue, any update on this?

iDevOrz avatar Apr 17 '24 15:04 iDevOrz

I believe it's not top priority, since it can be fixed by simply changing arrow function to function with body

AlexanderFarkas avatar Apr 17 '24 15:04 AlexanderFarkas