首页 > 解决方案 > 未处理的异常:NoSuchMethodError:方法“toDate”在 null 上被调用

问题描述

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

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

Timestamp转换为DateTimeusing时出错toDate()

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

请考虑这个 GIF

这个

这是 FIRESTORE DATATYPE 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
  }
}

提前致谢。

标签: dartfluttergoogle-cloud-firestore

解决方案


它显示错误,因为在 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);

希望它有帮助,为我工作:)


推荐阅读