在 Flutter 列表视图中删除 Firestore 数据 [英] Deleting Firestore Data in Flutter List View

查看:38
本文介绍了在 Flutter 列表视图中删除 Firestore 数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个从 Firestore 获取一些数据的常规列表视图,这是它的代码:

I have a regular List View that fetches some data from Firestore, here is the code for it:

body: StreamBuilder(
      stream: FirebaseFirestore.instance.collection('orders').snapshots(),
      builder: (context, snapshot) {
        if (!snapshot.hasData)
          return Center(
            child:
                CircularProgressIndicator(), 
          );
        return ListView.builder(
       
          itemCount: snapshot.data.docs.length,
          itemBuilder: (context, index) {
            DocumentSnapshot ds = snapshot.data.docs[index];
  
            return Text(ds['name']);

现在如果我想在其中的某处创建一个删除按钮,我会这样做:

Now if I wanted to create a delete button somewhere in it, I would do something like this:

FirebaseFirestore.instance.collection('orders').doc('ID SHOULD BE HERE').delete();

我的问题是如何在此处找到列表磁贴的文档 ID,以便从数据库中自动删除它?ID 应该在这里 代码中应该是一些命令来查找它的 ID,如下面的屏幕截图所示:

The issue I have is how do I find the document ID of the list tile on here in order to delete it automatically from the database? ID SHOULD BE HERE in the code should be some command to find the id of it like in the screenshot below:

推荐答案

DocumentSnapshot 包含一个名为 id 的属性,它将返回此快照的文档给定 ID.因此,您可以执行以下操作:

DocumentSnapshot contains a property called id which will return the document's given ID for this snapshot. Therefore you can do the following:

itemBuilder: (context, index) {
  DocumentSnapshot ds = snapshot.data.docs[index];
  print(ds.id);
  return Text(ds['name']);

然后根据id删除,操作如下:

And then to delete it according to the id, do the following:

FirebaseFirestore.instance.collection('orders').doc(ds.id).delete();

这篇关于在 Flutter 列表视图中删除 Firestore 数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆