I'm using json_serializable to generate code. One of my classes has a member variable(legislature) that is of type DocumentReference
and when I run the generator I get:
Error running JsonSerializableGenerator
Could not generate `fromJson` code for `legislature`.
None of the provided `TypeHelper` instances support the defined type.
When I remove the legislature the generator works as expected. Are type DocumentReference
not supported?
Not really - the library is pretty explicit that it only expects to support valid JSON types on the output side.
valid JSON type such as String, int, or Map<String, dynamic>.
Source
However there is a workaround. Although DocumentReference
is a valid class to pass through to FlutterFire in a Map<String, object?>
(particularly in combination with toJson
and fromJson
arguments to withConverter
on DocumentReference
or CollectionReference
objects, which is probably why you're doing this in the first place!), it is not a valid type for JsonSerializable, which expects only types which can passed directly to json.
A really simple workaround is by extending JsonConverter
and creating a customer serializer which you then annotate your class with, eg. by placing a @DocumentSerializer()
annotation.
class DocumentSerializer
implements JsonConverter<DocumentReference, DocumentReference> {
const DocumentSerializer();
@override
DocumentReference fromJson(DocumentReference docRef) => docRef;
@override
DocumentReference toJson(DocumentReference docRef) => docRef;
}
This then compiles neatly, provided you've not specified a type to the document reference.
Note that due to https://github.com/google/json_serializable.dart/issues/822 you'll need a seperate class (implements JsonConverter<DocumentReference?, DocumentReference?>
) if you want to support `DocumentReference?.
Any classes that you've already annotated with @JsonSerializable()
that use the DocumentReference type will also need to be annotated with @DocumentSerializer()
, eg.
@JsonSerializable()
@DocumentSerializer()
class MyClass {
DocumentReference myDocRef;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With