gpt4 book ai didi

firebase - Flutter - 删除一个 firebase 文档 onTap()

转载 作者:IT王子 更新时间:2023-10-29 07:23:58 24 4
gpt4 key购买 nike

我有一个 ListView,其中填充了作为聊天消息的 Firebase 集合。

当用户长按 ListTile(列表中的一个项目)时,我会显示一个 BottomSheet。

当用户单击 BottomSheet 上的 Delete 按钮时,应删除该文档。在点击“删除”按钮后,我无法找到删除所选文档的方法。

ListView 小部件:

return ListView.builder(
padding: new EdgeInsets.all(8.0),
reverse: true,
itemCount: snapshot.data.documents.length,
itemBuilder: (_, int index) {
var message = snapshot.data.documents[index]["content"];
var from = snapshot.data.documents[index]["idFrom"];
return new ListTile(
leading: new CircleAvatar(
backgroundColor: Colors.blue,
child: new Image.network(
"http://res.cloudinary.com/kennyy/image/upload/v1531317427/avatar_z1rc6f.png")),
title: new Row(
children: <Widget>[
new Expanded(child: new Text(message))
]
),
subtitle: new Text(from),
onLongPress: () {
showModalBottomSheet<void>(context: context,
builder: (BuildContext context) {
return Container(
child: new Wrap(
children: <Widget>[
new ListTile(
leading: new Icon(Icons.delete),
title: new Text('Delete'),
onTap: () =>
// Remove the tapped document here - how?
print(snapshot.data.documents[index]["id"])
Firestore.instance.collection("chats").document("ROOM_1")
.collection("messages").document(snapshot.data.documents[index]["id"])
.delete();
)
)
]
)
);
});
}
);
});

我需要找到一种方法来删除 onTap() 方法中的文档。不知道为什么,但即使我这样做了:

 onTap: () => {
// Remove the tapped document here - how?
const id = snapshot.data.documents[index]["id"];
},

IDE 返回错误 Expected an identifier

最佳答案

要删除文档,我们可以使用 Firestore.instancerunTransaction 方法和 delete 方法事务类。

await Firestore.instance.runTransaction((Transaction myTransaction) async {
await myTransaction.delete(snapshot.data.documents[index].reference);
});

代替

Firestore.instance.collection("chats").document("ROOM_1")  
.collection("messages").document(snapshot.data.documents[index]["id"])
.delete();

这是删除 doc1 文档之前我的虚拟数据库的外观:

enter image description here

删除 doc1 后:

enter image description here

关于firebase - Flutter - 删除一个 firebase 文档 onTap(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53994972/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com