首页 > 解决方案 > 删除用户评论给出值 null 颤振 Firestore

问题描述

我正在尝试使用户能够删除评论。然而,这段代码

deleteComment(BuildContext context) async {
  DocumentSnapshot doc = await 
    commentRef.doc(widget.post.postId).collection('comments')
    .doc('commentId').get();
  CommentModel comment = CommentModel.fromJson(doc.data());
  commentRef.doc(widget.post.postId).collection('comments')
    .doc(comment.commentId).delete();
 }

给我错误:

[ERROR:flutter/lib/ui/ui_dart_state.cc(199)] Unhandled Exception: 
NoSuchMethodError: The method '[]' was called on null.
E/flutter (23933): Receiver: null
E/flutter (23933): Tried calling: []("username")
E/flutter (23933): #0      Object.noSuchMethod (dart:core- 
patch/object_patch.dart:54:5)
E/flutter (23933): #1      new CommentModel.fromJson 
(package:blahblah/comments.dart:17:20)
E/flutter (23933): #2      _CommentsState.deleteComment 
(package:blahblah/comment.dart:465:41)
E/flutter (23933): <asynchronous suspension>
E/flutter (23933): 

在我的评论模型类中,我确实有一个用户名,与我的 firestore 集合中的用户名相同。为什么这会是空的?谢谢

火库收藏

更新:

我已将方法更新为:

deleteComment(BuildContext context) async {
DocumentReference documentReference = 
commentRef.doc(widget.post.postId).collection('comments').doc();
await commentRef.doc(widget.post.postId).collection('comments')
.doc(documentReference.id).delete();
}

它什么也不做!我认为,我没有正确引用文档 ID,因为我尝试将文档 ID 设置为 userId,然后删除文档(用户 ID),它起作用了。我的添加评论方法是:

addComments() async {
bool isBlocked = true == await 
blockedRef.doc(widget.post.postId).collection('blocked')
.where('blockingUserId', isEqualTo: 
widget.post.userId).where('blockedUserId', isEqualTo: currentUserId());
String commentsTEC = filter.censor(commentTEC.text);
DocumentSnapshot doc = await usersRef.doc(currentUserId()).get();
user = UserModel.fromJson(doc.data());

if (!isBlocked)
commentRef.doc(widget.post.postId).collection("comments")
.doc().set({
  "username": user.username,
  "comment": commentsTEC,
  "timestamp": timestamp,
  "userDp": user.photoUrl,
  "userId": user.id,
});
else {
  showInSnackBar(Languages.of(context).userIsBlocked);
}

请帮助我,正确引用文档。谢谢!

标签: fluttergoogle-cloud-firestore

解决方案


commentId您的屏幕截图中没有指定文档。您的意思是使用commentId变量而不是静态字符串吗?

DocumentSnapshot doc = await 
  commentRef.doc(widget.post.postId).collection('comments')
  .doc(commentId).get();
  //    remove "" here

推荐阅读