Flutter app error - type 'Timestamp' is not a subtype of type 'DateTime'

后端 未结 14 1355
刺人心
刺人心 2020-12-16 12:49

I\'m fetching data cloud firestore & trying to show in my app by using the following piece of code.

new Text(timeago.format(document.data[\'tripDoc\'][\'         


        
相关标签:
14条回答
  • 2020-12-16 13:08

    Try document.data["data"].microsecondsSinceEpoch

    This is working for me:-

    User.fromDocument(DocumentSnapshot document){
    dataNasc = DateTime.fromMicrosecondsSinceEpoch(document.data["data"].microsecondsSinceEpoch);
    }
    
    0 讨论(0)
  • 2020-12-16 13:12
    DateTime.fromMillisecondsSinceEpoch(timeStamp);
    DateTime.fromMicrosecondsSinceEpoch(timeStamp);
    
    0 讨论(0)
  • 2020-12-16 13:13

    If you use JsonSerializable, 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");
    }
    
    0 讨论(0)
  • 2020-12-16 13:15

    The Cloud Firebase timestamp field type has the structure:

    Timestamp (Timestamp(seconds=1561186800, nanoseconds=0))
    hashCode:423768083
    microsecondsSinceEpoch:1561186800000000
    millisecondsSinceEpoch:1561186800000
    nanoseconds:0
    runtimeType:Type (Timestamp)
    seconds:1561186800
    _seconds:1561186800
    _nanoseconds:0
    

    So you can use either micro- or milliseconds:

    DateTime.fromMillisecondsSinceEpoch(data['tripDoc']['docCreatedOn'].millisecondsSinceEpoch)
    

    or

    DateTime.fromMicrosecondsSinceEpoch(data['tripDoc']['docCreatedOn'].microsecondsSinceEpoch)
    
    0 讨论(0)
  • 2020-12-16 13:17

    You can try this..

    timeago.format(DateTime.tryParse(timestamp))
    

    like in yours it will be

      timeago.format(DateTime.tryParse(document.data['tripDoc']['docCreatedOn']))
    
    0 讨论(0)
  • 2020-12-16 13:18

    For some funny reason, I can't use toDate() on Android. Have to use it for iOS. So I'm forced to use a platform check like this:

    Theme.of(context).platform == TargetPlatform.iOS
      ? DateFormat('dd MMM kk:mm').format(document['timestamp'].toDate())
      : DateFormat('dd MMM kk:mm').format(document['timestamp'])
    
    0 讨论(0)
提交回复
热议问题