未处理的异常:NoSuchMethodError:在 null 上调用了方法“toDate”

May*_*ati 6 dart flutter google-cloud-firestore

我正在使用Firebase开发聊天应用程序。

一段时间以来我收到了这个错误 Unhandled Exception: NoSuchMethodError: The method 'toDate' was called on null.

Timestamp转换为DateTime使用时出现错误toDate()

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

请考虑这个 GIF

这

这是 Firestore 数据类型 AS TimeStamp

在此输入图像描述

源代码

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
  }
}
Run Code Online (Sandbox Code Playgroud)

提前致谢。

Maz*_*him 2

您的代码试图在获取之前转换time为,一个简短的解决方法是在服务器值加载之前使用当前时间初始化您的变量:Datetime

  Timestamp time = new Timestamp( new Date(2019,3,4) );
Run Code Online (Sandbox Code Playgroud)

另一种解决方案是在转换之前对服务器中的值使用一种async方法await,但考虑到您想在即时消息中使用它,您无法承受这种方法。更多内容可以在官方 Firebase 文档android 开发人员文档中找到。

请注意,上述代码将导致Timestamp指向午夜,但这应该不是问题,因为与 Firebase 响应速度相比,它只是一个简短的占位符。