在 Flutter 列表视图中删除 Firestore 数据 [英] Deleting Firestore Data in Flutter List View
问题描述
我有一个从 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屋!