Suppose this were my freezed class:
@freezed
class User with _$User {
factory User({
required String uuid,
required UniqueKey key,
@Default('') String name,
}) = _User;
factory User.initial() => User(
uuid: '',
key: UniqueKey(),
);
factory User.fromJson(Map<String, dynamic> json) =>
_$UserFromJson(json);
}
This throws an error Could not generate fromJson code for key.
So I tried
factory User.fromJson(Map<String, dynamic> json) =>
_$UserFromJson({...json, 'key': UniqueKey()});
but this is not valid either. It says "to support UniqueKey you can use JsonConverter"- I don't understand how to.
I also tried adding @JsonKey(includeFromJson: false, includeToJson: false)
but that throws another error.
Suppose this were my freezed class:
@freezed
class User with _$User {
factory User({
required String uuid,
required UniqueKey key,
@Default('') String name,
}) = _User;
factory User.initial() => User(
uuid: '',
key: UniqueKey(),
);
factory User.fromJson(Map<String, dynamic> json) =>
_$UserFromJson(json);
}
This throws an error Could not generate fromJson code for key.
So I tried
factory User.fromJson(Map<String, dynamic> json) =>
_$UserFromJson({...json, 'key': UniqueKey()});
but this is not valid either. It says "to support UniqueKey you can use JsonConverter"- I don't understand how to.
I also tried adding @JsonKey(includeFromJson: false, includeToJson: false)
but that throws another error.
1 Answer
Reset to default 1Option 1. Remove
factory User.fromJson(Map<String, dynamic> json) =>
_$UserFromJson(json);
from your freezed class, if you don't need the object to be serializable to json.
Option 2. If you do need it to be serializable to json then you can't use UniqueKey. You can instead generate a unique number and put that in the freezed class, and then use ValueKey(that number) to get a key.