0
@JsonSerializable()
class ParentClass {
  @TimestampSerializer()
  final DateTime createdAt;

  ParentClass({
    required this.createdAt,
  });

  factory ParentClass.fromJson(Map<String, dynamic> json) =>
      _$ParentClassFromJson(json);
}

@JsonSerializable()
class SubClass extends ParentClass {
  @TimestampSerializer()
  final DateTime updatedAt;

  SubClass({
    required createdAt,
    required this.updatedAt,
  }) : super(
          createdAt: createdAt,
        );

  factory SubClass.fromJson(Map<String, dynamic> json) =>
      _$SubClassFromJson(json);
}

in the situation above, i am getting error like below when i try to get SubClass.fromJson()

Unhandled Exception: type 'Timestamp' is not a subtype of type 'DateTime'

i am getting my data(createdAt and updatedAt) from firebase firestore. Both are timestamp types and the error kind of makes sense.

Is there a way to cast timestamp to datetime in this situation? i just want to use json_serializable.

Seung Joo Noh
  • 81
  • 1
  • 2
  • 6
  • 1
    I don't know `JsonSerializable` but the casting should work like: `DateTime createdAt = (data['createdAt'] as Timestamp).toDate()`, if your data from Firestore is in `data`. – Peter Koltai Aug 30 '23 at 13:24
  • Same as Peter's recommend, but with a source: https://stackoverflow.com/questions/75796805/json-serializable-cant-convert-datetime-to-timestamp-for-firestore – Frank van Puffelen Aug 30 '23 at 13:47

0 Answers0