'Flutter - remove a firebase document onTap()
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
Solution 1:[1]
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
:
Solution 2:[2]
If you know document id, You can delete easily.
Future<void> rejectJob(String jobId){
return _db.collection('jobs').document(jobId).delete();
}
Solution 3:[3]
Update 2021:
Add the following code to your button's onPressed
method.
final collection = FirebaseFirestore.instance.collection('collection');
collection
.doc('some_id') // <-- Doc ID to be deleted.
.delete() // <-- Delete
.then((_) => print('Deleted'))
.catchError((error) => print('Delete failed: $error'));
Solution 4:[4]
Deleting your document using .delete()
method on DocumentReference, will only removes the document fields and not the nested collections and its data in the document.
Using runTransactions()
method on FirebaseFirstore.instance
deletes the documemt completely without leaving any collection or data behind as suggested by Jerome Escalante.
FireBaseFirestore.instance.runTransactions((transaction) async =>
await transaction.delete(DocumentReference));
So, use runTransactions()
instead of delete()
method.
Solution 5:[5]
for simple and quick method try this (especially if you use login/signup)
Future deleteData(String id) async{
try {
await FirebaseFirestore.instance
.collection("users")
.doc(FirebaseAuth.instance.currentUser!.uid)
.collection("collection_name")
.doc(id)
.delete();
}catch (e){
return false;
}
}
then under the delete button you can pass the deleteData function
onPressed:() {
deleteData(collection_name.id);
Navigator.pop(context);
}, //delete
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | BIS Tech |
Solution 3 | CopsOnRoad |
Solution 4 | balu k |
Solution 5 | Leonard Udum |