json_serializable: Selecting JsonConverter's at runtime

I'm looking for a solution on how I could switch what JsonConverter I am using at runtime with the package:json_serializable package. This will allow my app use DateTime objects but then convert these to/from Firestore Timestamp objects only when required (when communicating with Firestore).

I need a solution that would allow me to share the data models in none-flutter/firestore environments and they just work as expected as DateTime objects.

Current solution (built_value)

My app that shares it's data models between flutter apps, Dart-SDK only environments (GCP Cloud Run) and firestore. I currently use package:built_value and I have two sets of serializers (dartSerializers & firestoreSerializers). This allows me to choose which I use, see example below:

FooBar.fromJsonMap(
      Serializers serializers, Map<String, dynamic> data) => 
         serializers.deserializeWith(ChatMessage.serializer, data)!;

 Map<String, dynamic> toJsonMap(Serializers serializers) =>
         Map.of(serializers.serialize(this, //....

Thanks

Upvotes: 2

Views: 32

Answers (1)

Bram
Bram

Reputation: 680

I'm not entirely sure what you're trying to accomplish, but why can't you write a single converter that - when called - branches to use one or the other way to deserialize, based on a global variable that represents the environment the code is running in?

Upvotes: 0

Related Questions