Flutter JSON serializable using json_annotation package how to use JsonConverter with Firebase Firestore DocumentReference

Viewed 314

I'm trying to save a DocumentReference in models using JSON serializable with a custom JsonConverter but not doing it correct

here is my model

@DocumentSerializer()
DocumentReference? recentTrainingRef;

My DocumentSerializer Class

class DocumentSerializer
    implements JsonConverter<DocumentReference, DocumentReference> {
  const DocumentSerializer();

  @override
  DocumentReference fromJson(DocumentReference docRef) => docRef;

  @override
  DocumentReference toJson(DocumentReference docRef) => docRef;
}

I'm getting the following error Could not generate fromJson code for recentTrainingRef.

1 Answers

As noted in my answer Are type DocumentReference supported by json_serializable?, due to https://github.com/google/json_serializable.dart/issues/822, you need a nullable document serializer because your type (DocumentReference?) is nullable (because of the ? at the end).

Quite simply (and you'll need to add @DocumentSerializerNullable() annotation before the class you're trying to use it with).

class DocumentSerializerNullable
    implements JsonConverter<DocumentReference?, DocumentReference?> {
  const DocumentSerializerNullable();

  @override
  DocumentReference? fromJson(DocumentReference? docRef) => docRef;

  @override
  DocumentReference? toJson(DocumentReference? docRef) => docRef;
}
Related