freezed
freezed copied to clipboard
Generic arguments with JsonSerializable
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
I'm having the same issue, any update on this?
I believe it's not top priority, since it can be fixed by simply changing arrow function to function with body