I have a ListView, filled with Firebase collection as chat messages.
When the user long press a ListTile (an item on the list), I show a BottomSheet.
When the user clicks the Delete
button on the BottomSheet, the document should be removed. I'm unable to find a way to remove the selected document after tapping the "Delete" button.
The listview widget:
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();
)
)
]
)
);
});
}
);
});
I need to find a way to remove the document in the onTap()
method. not sure why, but even when I do:
onTap: () => {
// Remove the tapped document here - how?
const id = snapshot.data.documents[index]["id"];
},
the IDE retruns an error Expected an identifier
To delete a document, we can use the runTransaction
method of the Firestore.instance
and use the delete
method of the Transaction
class.
await Firestore.instance.runTransaction((Transaction myTransaction) async {
await myTransaction.delete(snapshot.data.documents[index].reference);
});
instead of
Firestore.instance.collection("chats").document("ROOM_1")
.collection("messages").document(snapshot.data.documents[index]["id"])
.delete();
Here is the look of my dummy database before the deletion of doc1
document:
After deleting doc1
:
If you know document id, You can delete easily.
Future<void> rejectJob(String jobId){
return _db.collection('jobs').document(jobId).delete();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With