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

如何在Firestore中获取postID以删除对应文档

Firestore 删除对应文档解决方案

1. 提前获取文档ID(postID)

你在渲染thread集合对应的列表数据时,拉取到的每个DocumentSnapshot实例都自带documentID属性,这个属性就是你需要的对应文档的唯一ID,你只需要将这个ID绑定到对应列表项的组件参数中即可。
示例拉取逻辑:

StreamBuilder<QuerySnapshot>(
  stream: Firestore.instance.collection('thread').snapshots(),
  builder: (context, snapshot) {
    if (!snapshot.hasData) return CircularProgressIndicator();
    return ListView.builder(
      itemCount: snapshot.data.documents.length,
      itemBuilder: (context, index) {
        DocumentSnapshot currentDoc = snapshot.data.documents[index];
        // 这里拿到的就是对应文档的postID,传入列表项组件
        String postId = currentDoc.documentID;
        return ThreadListItem(postId: postId, docData: currentDoc.data);
      },
    );
  }
)

2. 修改删除逻辑

你现有代码中document()方法没有传入参数,会生成一个全新的随机ID文档引用,无法指向你要删除的目标文档,你需要把前面拿到的postId传入该方法即可。
修改后的PopupMenuButton代码:

// 所在组件先接收传递过来的postId参数
final String postId;

PopupMenuButton<int>(
  itemBuilder: (context) => [
    PopupMenuItem(
      value: 1,
      child: Row(
        children: [
          Padding(
            padding: const EdgeInsets.only(right: 8.0, left: 8.0),
            child: Icon(Icons.report),
          ),
          Text("delete")
        ],
      ),
    ),
  ],
  initialValue: 1,
  onCanceled: () {
    print("You have canceled the menu.");
  },
  onSelected: (value) {
    Firestore.instance
      .collection("thread")
      .document(postId) // 传入对应文档的postId
      .delete()
      .then((_) {
        print("success!");
      })
      .catchError((err) {
        print("delete failed: $err");
      });
  },
),

补充说明

如果你没有使用Firestore自动生成的文档ID,而是自己在文档字段中存储了自定义的postID,你可以先通过where条件查询匹配到对应文档,再获取文档ID执行删除操作,不过直接使用Firestore自带的documentID性能更高、逻辑更简单。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 04:18:00