Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/flutter/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Dart 未处理的异常:NoSuchMethodError:方法';今天';被调用为空_Dart_Flutter_Google Cloud Firestore - Fatal编程技术网

Dart 未处理的异常:NoSuchMethodError:方法';今天';被调用为空

Dart 未处理的异常:NoSuchMethodError:方法';今天';被调用为空,dart,flutter,google-cloud-firestore,Dart,Flutter,Google Cloud Firestore,我正在使用Firebase开发聊天应用程序 一段时间以来,我一直收到此错误未处理的异常:NoSuchMethodError:方法“toDate”在null上被调用。 使用toDate()将Timestamp转换为DateTime时出错 给出一段时间的错误,然后错误消失。 请考虑此GIF < /强> 以下是FIRESTORE数据类型,即时间戳 源代码 class ChatMessageModel { bool isSentByMe; String msg = ''; ///S

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

一段时间以来,我一直收到此错误
未处理的异常:NoSuchMethodError:方法“toDate”在null上被调用。

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

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

<强>请考虑此GIF < /强>

以下是FIRESTORE数据类型,即时间戳

源代码

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
  }
}

提前感谢。

您的代码试图在提取之前将
时间
转换为
日期
,一个简单的解决方法是在服务器值加载之前用当前时间初始化
时间
变量:

  Timestamp time = new Timestamp( new Date(2019,3,4) );
另一个解决方案是使用
async
方法
等待服务器的值,然后再进行转换,这是你无法承受的,因为你想在即时消息中使用它。更多信息可以在官方Firebase和android开发者中找到

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

试试换衣服

this.localTime = this.time.toDate();


为了更好的可读性,请将
this.time.toDate()
保存在一个变量中。希望对我有帮助,请尝试
snapshot.data['time']。toDate
已尝试。没有任何更改。似乎
firestore
api中存在错误
StreamBuilder
的builder方法调用了2次,第一次调用空值
timestamp
,第二次调用非空值?我在Flash聊天应用程序中遇到了完全相同的错误。
DateTime.now().millissecondssinceepoch
无法转换为时间戳。我更正了错误,希望它能解决您的问题。我正在收听firebase流,直到我知道流仅在该流中的某些值更改时更新值。因此,数据必须以快照的形式加载。
this.localTime = this.time.toDate()==null?DateTime().now():this.time.toDate();