I want to add a custom converter to a freezed class like in this answer.
I tried it with this code:
@freezed
class NewsPost with _$NewsPost {
factory NewsPost({
@JsonKey(name: "date") @TimestampConverter() DateTime? date,
}) = _NewsPost;
factory NewsPost.fromJson(Map<String, dynamic> json) =>
_$NewsPostFromJson(json);
}
But it did not work. Any ideas are more than welcome!
For your interest, this is my Converter:
class TimestampConverter implements JsonConverter<DateTime, Timestamp> {
const TimestampConverter();
@override
DateTime fromJson(Timestamp timestamp) {
return timestamp.toDate();
}
@override
Timestamp toJson(DateTime date) => Timestamp.fromDate(date);
}
Thank you :-)
Since null safety was introduced, for
JsonConverter
to work with thefreezed
generator the nullability of the types declared inJsonConverter
need to match the nullability of the type in the freezed class.If the types do not match,
freezed
ignores the converter.So using your example:
Tested and working on flutter 2.5.3 with the following dependency versions: