dart - 未处理的异常:NoSuchMethodError:方法“toDate”在 null 上被调用
问题描述
我正在使用Firebase开发一个聊天应用程序。
有一段时间我收到这个错误 Unhandled Exception: NoSuchMethodError: The method 'toDate' was called on null.
Timestamp
转换为DateTime
using时出错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
}
}
提前致谢。
解决方案
它显示错误,因为在 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);
希望它有帮助,为我工作:)
推荐阅读
- python-3.x - 有没有一种方法可以从这个特定的字典中创建一个多索引数据帧来保持数据的完整性?
- python-3.x - 在linux中使用不同的pid重复相同的进程
- javascript - 每次发送电子邮件时如何在每行中标记一个单元格
- sql - Joins和count相关的SQL查询
- openstreetmap - 如何在 overpass-turbo 中正确合并关系、节点和方式?
- python - Jupyter / IPython SList ::从shell执行运算符“!”获取非标记化输出
- python-3.x - “无效的继续字节” Python Socket
- powershell - 通过 Powershell 更改服务帐户密码给我错误 1609 但密码正确
- javascript - DELETE前如何处理OPTIONS方法?
- ios - 超出范围,线程问题