dart - 未处理的异常 : NoSuchMethodError: The method 'toDate' was called on null

标签 dart flutter google-cloud-firestore

我正在使用 开发一个聊天应用程序火力基地 .

有一段时间我收到此错误 Unhandled Exception: NoSuchMethodError: The method 'toDate' was called on null.
转换时出错 TimestampDateTime使用 toDate() .

在一段时间内出现错误,然后错误消失。

请考虑这个 GIF .

THIS

这是火灾存储数据类型为 TimeStamp .

enter image description here

源代码

class ChatMessageModel {
  bool isSentByMe;
  String msg = '';

  ///SERVER TIME
  Timestamp time;
  DateTime localTime;
  String timeStamp;
  String fromUid;
  String toUid;

  ChatMessageModel._();

  ChatMessageModel.fromSnapshot(DocumentSnapshot snapshot) {
    this.isSentByMe =
        snapshot.data['from'] == LoginBloc.instance.firebaseUser.uid;
    this.msg = snapshot.data['msg'];
    this.timeStamp = snapshot.data['time'].toString();
    this.time = snapshot.data['time'];
    this.fromUid = snapshot.data['from'];
    this.toUid = snapshot.data['to'];
    this.localTime = this.time.toDate(); //ERROR
  }
}

提前致谢。

最佳答案

它显示错误,因为在 this.time 的调用时间,
this.time 为空。所以 toDate() 函数不能应用于 null
尝试更改:this.localTime = this.time.toDate(); 至:

this.localTime = this.time == null ? DateTime.now()
    : this.time.toDate();
或者你可以这样使用:
String stringtime = widget.time == null
        ? DateTime.now().toString()
        : widget.time.toDate().toString();
    // stringtime = widget.time.toDate().toString();
    DateTime date = DateTime.parse(stringtime);
    String clocktime = DateFormat('hh:mm a').format(date);
希望它对我有用:)

关于dart - 未处理的异常 : NoSuchMethodError: The method 'toDate' was called on null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54985317/

相关文章:

dart - Material 设计<style>元素放置

http - flutter:内容类型必须是 application/json

class - flutter , Dart 。创建匿名类

dart - Flutter:Tabbar 的 spaceBetween 如何布局

java - 如何在 Firestore 数据库中运行多个事务?我面临的问题是

ios - 无法在 Android Studio 中为 Flutter 选择 iOS Phone Simulator

flutter - 如何在点击 FAB 时显示卡片?

ios - 如何从 Flutter 平台启动 ViewController 特定于 Swift 编写的代码?

javascript - Node.js Firestore 查询选择字段路径列表

javascript - 我不知道如何在 case admin.firestore 中设置 firebase firestore.settings?