'Delete a document from firebase
I'm building an app that contains pet adoption offers. Each pet document has an ID that's generated by DateTime.now() + the user ID to make it unique, anyway, I'm trying to write a deleting method within the Slidable widget to delete the adoption offer. The problem is that I'm unable to reach the document ID to delete it.
Is there a way to delete a document without getting the ID?
This is the Firebase database

Here is my current code
Future getOffersList() async {
List<PetTile> tiles = [];
List<Slidable> slidables = [];
var data = await FirebaseFirestore.instance
.collection('pets')
.where('owner',
isEqualTo: FirebaseAuth.instance.currentUser!.uid.toString())
.get();
_petsList = List.from(data.docs.map((doc) => Pet.fromSnapshot(doc)));
for (var pet in _petsList) {
tiles.add(PetTile(pet: pet));
}
for (var tile in tiles) {
slidables.add(
Slidable(
child: tile,
endActionPane: ActionPane(
motion: const DrawerMotion(),
children: [
SlidableAction(
onPressed: (value) async {
var ref = FirebaseFirestore.instance
.collection('pets')
.where('id', isEqualTo: tile.pet.id)
.get();
// Deleting...
},
backgroundColor: Color(0xFFFE4A49),
foregroundColor: Colors.white,
icon: Icons.delete,
label: 'Delete',
),
],
),
),
);
}
}
Solution 1:[1]
You can get the id of the document by doing the following steps:
Add await infront when you're accessing the conditioned data from firebase collection.. in your case in front of FirebaseFirestore.instance *This will return a QuerySnapshot rather than a Future instance of the same.
You need to get the doc and the id of that doc.. write: final id= ref.docs[0].id
*Using first index(0) because i am assuming that only one pet id matches with other pet id.
- since you have the id now.. you can perform the delete function
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 | Yash Bhansali |
