Home > Net >  Can't convert firetstore timestamp to Flutter DateTime
Can't convert firetstore timestamp to Flutter DateTime

Time:10-10

I can't convert firestore timestamp to flutter date, and really tried near everything( including using Timestamp instead of DateTime in model), any idea how to fix this bug. Here's my code below

Model From Map

  factory Event.fromMap(Map<String, dynamic> map) {
    return Event(
      id: map['id'],
      organizerId: map['organizerId'],
      organizerName: map['organizerName'],
      eventTime: map['eventTime'].toDate(),
      maxApplicationCount: map['maxApplicationCount'],
      attendedUsers: List<String>.from(map['attendedUsers']),
      eventText: map['eventText'],
      location: Location.fromMap(map['location']),
    );
  }

Error

 NoSuchMethodError: Class 'int' has no instance method 'toDate'.

Using Timestamp Instead of DateTime

  factory Event.fromMap(Map<String, dynamic> map) {
    return Event(
      id: map['id'],
      organizerId: map['organizerId'],
      organizerName: map['organizerName'],
      eventTime: map['eventTime'],
      maxApplicationCount: map['maxApplicationCount'],
      attendedUsers: List<String>.from(map['attendedUsers']),
      eventText: map['eventText'],
      location: Location.fromMap(map['location']),
    );
  }

Error

flutter: type 'int' is not a subtype of type 'Timestamp'

Any idea how to convert Firestore timestamp to dateTime?

map['eventTime']

Timestamp(seconds=1620583200, nanoseconds=0)

CodePudding user response:

Could you just make eventTime as dynamic and try eventModel.eventTime.toDate() wherever you use it

This works for me. Set and get timestamp like this

class EventModel{
      dynamic timestamp;
      SiteModel({this.deletedTimestamp});
      EventModel.fromJson(Map<String, dynamic> json) {
        timestamp=json['timestamp'];
      }
    
      Map<String, dynamic> toJson() {
        final Map<String, dynamic> data =<String, dynamic>{};
        data["timestamp"]=FieldValue.serverTimestamp();
        return data;
      }

Use it like this

eventModel.timestamp.toDate().toString()
  • Related