Gemu
Gemu

Reputation: 629

flutter: json_serializable how set converter globally

How can I set a converter globally to replace the buildin datetime for example?

this does not appear in the documentation

https://pub.dev/packages/json_serializable

replace the datetime converter with a custom one globally for all classes

Upvotes: 1

Views: 812

Answers (1)

Code on the Rocks
Code on the Rocks

Reputation: 17616

First, create your converter:

class DateTimestampConverter implements JsonConverter<DateTime?, Timestamp?> {
  const DateTimestampConverter();

  @override
  DateTime? fromJson(Timestamp? timestamp) => timestamp?.toDate();

  @override
  Timestamp? toJson(DateTime? dateTime) => dateTime != null ? Timestamp.fromDate(dateTime) : null;
}

Then add it to your @JsonSerializable annotation:

@JsonSerializable(
  explicitToJson: true,
  converters: [DateTimestampConverter()],
)

Upvotes: 0

Related Questions