Home > other >  Flutter JSON serializable using json_annotation package how to use JsonConverter with Firebase Fires
Flutter JSON serializable using json_annotation package how to use JsonConverter with Firebase Fires

Time:02-08

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.

CodePudding user response:

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 null document serializer because your type (DocumentReference) is nullable (because of the arrow at the end).

Quite simply (and @DocumentSerializerNullable() annotation).

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

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

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