如何解决Flutter Firestore出现NoSuchMethodError:方法'[]'被空对象调用的问题
问题根因
错误栈明确说明CommentModel.fromJson方法执行时,传入的json参数为null,调用json["docId"]时触发空指针异常,核心有两个触发点:
- 你调用
commentRef.doc(widget.post.postId).collection('comments').doc(widget.comment.docId).get()获取的评论文档不存在,导致snap.data()返回null,你没有做空判断就直接传入CommentModel.fromJson - 另外还有一个潜在问题:Firestore的文档ID默认不会存储在文档自身的字段中,如果你新增评论时没有主动把
docId字段写入文档内容,即使文档存在,snap.data()里也没有docId字段,后续也会出现取值异常。
修复方案
- 先增加文档存在性判断,避免空值传入fromJson
修改handleComments方法的前半段逻辑:
handleComments(BuildContext context) async { DocumentSnapshot snap = await commentRef.doc(widget.post.postId) .collection('comments').doc(widget.comment.docId).get(); // 新增文档存在性+空值判断 if (!snap.exists || snap.data() == null) { return; } CommentModel comment = CommentModel.fromJson(snap.data() as Map<String, dynamic>); // 后续保持原有逻辑不变 bool isMe = widget.post.userId == comment.userId; bool isComUser = currentUserId() == comment.userId; if (isMe || isComUser) showDialog( context: context, builder: (context) { return SimpleDialog( backgroundColor: Colors.red, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(15.0)), children: [ SimpleDialogOption( onPressed: () { deleteComment(context); }, child: Text(Languages .of(context) .deleteComment, style: TextStyle(color: Colors.white),), ), ], ); }); }
- 修复docId字段读取逻辑
不需要把docId冗余存在文档里,直接用快照的id属性即可,在fromJson调用后追加赋值:
CommentModel comment = CommentModel.fromJson(snap.data() as Map<String, dynamic>); // 直接取快照的文档ID赋值给docId comment.docId = snap.id;
如果你希望docId存储在文档字段中,只需要在新增评论的逻辑里,写入文档时主动把生成的docId作为字段存入即可。
- 可选优化:给CommentModel增加空安全兼容,避免类似异常
CommentModel.fromJson(Map<String, dynamic> json) { username = json['username'] ?? ''; comment = json['comment'] ?? ''; timestamp = json['timestamp']; userDp = json['userDp'] ?? ''; userId = json['userId'] ?? ''; docId = json['docId'] ?? ''; }
内容的提问来源于stack exchange,提问作者HaKim
相关产品推荐
相关产品推荐

