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

后端 未结 14 1357
刺人心
刺人心 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:19

    .toDate() worked for me. Now the modified code is -

    new Text(timeago.format(document.data['tripDoc']['docCreatedOn'].toDate()))
    

    Hope, it'll help someone.

    0 讨论(0)
  • 2020-12-16 13:20

    I think this is more reliable

    DateTime updateDateTime = DateTime.fromMillisecondsSinceEpoch(
            map['updatedatetime'].millisecondsSinceEpoch);
    
    0 讨论(0)
  • 2020-12-16 13:20

    This could also be an error because in the database or firebase there is some type that is missing or different name on

    0 讨论(0)
  • 2020-12-16 13:25
    var date = DateTime.fromMillisecondsSinceEpoch(timestamp)
    
    0 讨论(0)
  • 2020-12-16 13:25

    It is irrelavant but for those who use Timestamp (cloud_firestore) instead of DateTime you probably will get

    <String, dynamic>' is not a subtype of type 'Timestamp'

    class MyUser {
      String uid;
      String email;
      Timestamp firstJoined;
      
      MyUser.fromJson(Map<String, dynamic> data) {
        this.uid = data['uid'] ?? '';
        this.email = data['email'] ?? '';
        // PARSE FIRESTORE TIMESTAMP
        if (data['firstJoined'] != null) {
            this.firstJoined = Timestamp(
                data['firstJoined']['_seconds'],
                data['firstJoined']['_nanoseconds'],
            );
        } else {
            this.firstJoined=null;
        }
      }
    }
    
    0 讨论(0)
  • 2020-12-16 13:27

    Ios and Android will not receive same type. Ios receive the timestamps as TimeStamp and Android receive it as DateTime already. So for fixing this issue I just created this little function. This will return a DateTime and let use format it etc.

    import 'dart:io';
    
    import 'package:cloud_firestore/cloud_firestore.dart';
    
    DateTime parseTime(dynamic date) {
      return Platform.isIOS ? (date as Timestamp).toDate() : (date as DateTime);
    }
    
    0 讨论(0)
提交回复
热议问题