How do I resolve type 'Timestamp' is not a subtype of type 'String' in type cast
Thanks to @Reed, for pointing to the right direction. When passing DateTime
value to FireStore
there seem no issues for firebase to take that value as Timestamp
, however when getting it back it needs to be properly handled. Anyways, here is example, that works both ways:
import 'package:cloud_firestore/cloud_firestore.dart'; //<-- dependency referencing Timestamp
import 'package:json_annotation/json_annotation.dart';
part 'test_date.g.dart';
@JsonSerializable(anyMap: true)
class TestDate {
@JsonKey(fromJson: _dateTimeFromTimestamp, toJson: _dateTimeAsIs)
final DateTime theDate;
TestDate({this.theDate,});
factory TestDate.fromJson(Map<String, dynamic> json) {
return _$TestDateFromJson(json);
}
Map<String, dynamic> toJson() => _$TestDateToJson(this);
static DateTime _dateTimeAsIs(DateTime dateTime) => dateTime; //<-- pass through no need for generated code to perform any formatting
// https://stackoverflow.com/questions/56627888/how-to-print-firestore-timestamp-as-formatted-date-and-time-in-flutter
static DateTime _dateTimeFromTimestamp(Timestamp timestamp) {
return DateTime.parse(timestamp.toDate().toString());
}
}
Use JsonConverter
class TimestampConverter implements JsonConverter<DateTime, Timestamp> {
const TimestampConverter();
@override
DateTime fromJson(Timestamp timestamp) {
return timestamp.toDate();
}
@override
Timestamp toJson(DateTime date) => Timestamp.fromDate(date);
}
@JsonSerializable()
class User{
final String id;
@TimestampConverter()
final DateTime timeCreated;
User([this.id, this.timeCreated]);
factory User.fromSnapshot(DocumentSnapshot documentSnapshot) =>
_$UserFromJson(
documentSnapshot.data..["_id"] = documentSnapshot.documentID);
Map<String, dynamic> toJson() => _$UserToJson(this)..remove("_id");
}