You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter Firestore实现用户删除评论功能时报null错误如何解决

错误原因

首次报错原因

你写死了查询的文档ID为固定字符串'commentId',Firestore中不存在对应ID的评论文档,所以get()返回的DocumentSnapshot数据为空,doc.data()为null,传入CommentModel.fromJson解析时读取username字段就触发了空对象调用异常。

二次修改无效果原因

你调用.doc()会生成一个全新的随机文档ID,和你已存储的评论文档ID完全不匹配,删除的是不存在的文档,自然没有任何作用。

正确实现方案

步骤1:修复添加评论逻辑,存储文档ID

你添加评论时使用了Firestore自动生成的随机文档ID,需要把这个ID存入评论字段中,方便后续读取和删除:

addComments() async {
  // 补充原逻辑缺失的get()调用,否则isBlocked判断永远错误
  final blockQuery = await blockedRef.doc(widget.post.postId).collection('blocked')
      .where('blockingUserId', isEqualTo: widget.post.userId)
      .where('blockedUserId', isEqualTo: currentUserId())
      .get();
  bool isBlocked = blockQuery.size > 0;

  String commentsTEC = filter.censor(commentTEC.text);
  DocumentSnapshot doc = await usersRef.doc(currentUserId()).get();
  user = UserModel.fromJson(doc.data());

  if (!isBlocked) {
    // 先获取自动生成的评论文档引用
    final commentDocRef = commentRef.doc(widget.post.postId).collection("comments").doc();
    // 把文档ID存入评论数据中
    await commentDocRef.set({
      "commentId": commentDocRef.id,
      "username": user.username,
      "comment": commentsTEC,
      "timestamp": timestamp,
      "userDp": user.photoUrl,
      "userId": user.id,
    });
  } else {
    showInSnackBar(Languages.of(context).userIsBlocked);
  }
}

步骤2:改造删除逻辑,传入目标评论ID

你在评论列表页面渲染每条评论时,都会持有对应评论的CommentModel实例,点击删除按钮时直接传入当前评论的commentId即可直接删除,不需要额外查询:

deleteComment(BuildContext context, String targetCommentId) async {
  await commentRef.doc(widget.post.postId)
      .collection('comments')
      .doc(targetCommentId)
      .delete();
}

内容的提问来源于stack exchange,提问作者HaKim

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 06:09:04