I want to toggle a favourites button using firestore. When i click on it initially, I want to add it to a collection, then clicking again should remove that exact item from the collection. My issue here is that, I could achieve this by setting the doc name to the title and simply delete using the title has reference. This would have an issue later on, since two products can technically have the same name. That is why I want to use the id has a reference name since it is dynamic. This is the code below.
try {
if (widget.product['isFavourited'] == true) {
String docId = widget.product.id;
// print(docId.toString());
// print(widget.product['isFavourited'].toString());
await FirebaseFirestore.instance
.collection('Products')
.doc(docId)
.update({'isFavourited': false}).then((value) async {
final CollectionReference collectionReference =
FirebaseFirestore.instance
.collection('Users')
.doc(uid)
.collection('Favourites');
await collectionReference
.doc()
.delete();
print('');
});
} else {
String docId = widget.product.id;
await FirebaseFirestore.instance
.collection('Products')
.doc(docId)
.update({'isFavourited': true}).then((value) async {
final CollectionReference collectionReference =
FirebaseFirestore.instance
.collection('Users')
.doc(uid)
.collection('Favourites');
final String id = collectionReference.doc().id;
final String itemtodelete = collectionReference.doc(id).id;
print(itemtodelete);
print(id);
await collectionReference.doc(itemtodelete).set({
'id': itemtodelete,
'title': widget.product['title'],
'price': widget.product['price'],
'about': widget.product['about'],
'description': widget.product['description'],
'imagepath': widget.product['imagepath'],
'isFavourited': widget.product['isFavourited'],
'isCarted': widget.product['isCarted'],
});
});
2
Answers
This code worked perfectly for me, given the way I structured my function. @Adnan Khan's answer was really helpful in figuring it out. I hope this helps someone who is stuck.
try is out hope this will help.
// productId is your productId = widget.product.id
// uid is your current user id
// favorite id is your each favorite documentId
}