I want to reference a category document in my post document in firebase. This is my data class, I'm also using freezed and json_serializer:
part 'post_dto.freezed.dart'; part 'post_dto.g.dart'; part 'category_dto.freezed.dart'; part 'category_dto.g.dart'; @freezed abstract class PostDTO with _$PostDTO { const PostDTO._(); const factory PostDTO({ @JsonKey(ignore: true) String? id, required String title, required String description, @DocumentReferenceConveter() DocumentReference? categoryReference, }) = _PostDTO; factory PostDTO.fromJson(Map json) => _$PostDTOFromJson(json); factory PostDTO.fromFireStore(DocumentSnapshot document) { Map data = document.data() as Map; return PostDTO.fromJson(data).copyWith(id: document.id); } } @freezed abstract class CategoryDTO with _$CategoryDTO { const CategoryDTO._(); const factory CategoryDTO({ required String icon, required String name, }) = _CategoryDTO; factory CategoryDTO.fromFireStore(DocumentSnapshot document) { Map data = document.data() as Map; return CategoryDTO.fromJson(data); } factory CategoryDTO.fromJson(Map json) => _$CategoryDTOFromJson(json); }
When I run build_runner I got this error:
[SEVERE] json_serializable:json_serializable on lib/infrastructure/post/post_dto.dart: Could not generate `fromJson` code for `categoryReference`. To support the type `DocumentReference` 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 package:UPLFY/infrastructure/post/post_dto.freezed.dart:373:41 ╷ 373 │ final DocumentReference? categoryReference; │ ^^^^^^^^^^^^^^^^^ ╵ [INFO] Running build completed, took 2.5s [INFO] Caching finalized dependency graph... [INFO] Caching finalized dependency graph completed, took 44ms [SEVERE] Failed after 2.5s
So tried using the JsonConverter but I'm not sure how to convert the json object to a DocumentReference...
class DocumentReferenceConveter implements JsonConverter, Object> { const DocumentReferenceConveter(); @override DocumentReference fromJson(Object json) { return //TODO: Convert json to DocumentReference } @override Object toJson(DocumentReference documentReference) => documentReference; }