【问题标题】:Firestore converting DateTime to TimeStampFirestore 将 DateTime 转换为 TimeStamp
【发布时间】:2020-12-15 00:34:16
【问题描述】:

firestore添加数据时,数据库将DateTime对象转换为TimeStamp 我的代码:

class JobApplication {
  DateTime time;
JobApplication({this.time});

JobApplication.fromMap(Map<String, dynamic> map)
  : time = map['time'] as DateTime;

Map<String, dynamic> toMap() {
return {
  'time': this.time,};
}

获取时显示以下错误

Expected a value of type 'DateTime', but got one of type 'Timestamp'

The relevant error-causing widget was: 
  StreamBuilder<QuerySnapshot> file:///home/koha/Projects/sirajulhuda_app/lib/screens/job_appli_screen.dart:56:24
When the exception was thrown, this was the stack: 
dart-sdk/lib/_internal/js_dev_runtime/private/ddc_runtime/errors.dart 212:49      throw_
dart-sdk/lib/_internal/js_dev_runtime/private/ddc_runtime/errors.dart 60:3        castError
dart-sdk/lib/_internal/js_dev_runtime/private/ddc_runtime/operations.dart 442:10  cast
dart-sdk/lib/_internal/js_dev_runtime/private/ddc_runtime/types.dart 411:9        as
packages/sirajulhuda_app/models/job_application.dart 72:26                        fromMap

【问题讨论】:

    标签: flutter google-cloud-firestore


    【解决方案1】:

    您需要将从 Firestore 获得的 TimeStamp 转换为 DateTime。

    像这样:

    Timestamp timestamp = // What you get from FireStore
    DateTime date = timeStamp.toDate();
    

    编辑

    class JobApplication {
      DateTime time;
     JobApplication({this.time});
    
    JobApplication.fromMap(Map<String, dynamic> map)
      : time = (map['time'] as Timestamp).toDate();
    
    Map<String, dynamic> toMap() {
      return {
        'time': this.time,};
    }
    

    【讨论】:

    • 我已经编辑了这个问题。如果我以stream 获取,如何将timeJobApplication 模型转换?
    • 我已经编辑了我的答案。只需将您的数据转换为时间戳并使用 toDate() 转换此时间戳
    猜你喜欢
    • 2022-01-02
    • 1970-01-01
    • 2016-10-19
    • 1970-01-01
    • 2011-11-21
    • 1970-01-01
    • 2015-04-20
    • 1970-01-01
    相关资源
    最近更新 更多