flutter - 删除用户评论给出值 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);
}
请帮助我,正确引用文档。谢谢!
解决方案
commentId
您的屏幕截图中没有指定文档。您的意思是使用commentId
变量而不是静态字符串吗?
DocumentSnapshot doc = await
commentRef.doc(widget.post.postId).collection('comments')
.doc(commentId).get();
// remove "" here
推荐阅读
- python - 绘制 3D 图形的列表操作(ndim - 错误)
- swift - 文档路径SwiftUI中随机生成的Firebase子键
- r - 根据 df1 和 df2 之间的匹配将列从 df2 添加到 df1
- python - tensorflow.keras.layers 和 keras.layers 有什么区别?
- javascript - 如何根据一个值过滤和修改数组?
- firebase - 由于错误的 Chrome 用户,来自邮件的 Firebase Crashlytics 链接重定向到错误页面
- kubernetes - 无法使用 hostNetwork 解析容器内的 Kubernetes 服务名称
- kubernetes - Hashicorp 领事,代理/客户访问
- python - 安装和运行 Tensorflow 时出现 ValueError
- spring-boot - 带有 ConfigurationProperties 的 Spring Boot CORS 配置