Reputation: 65
I am new in flutter, I am facing a problem which is how to delete Firestore photos.
I have created a Subcollection where I am storing my products details, this product also contains an image that is stored in Firebase Storage. If delete my product, like I have 10 products but I want to delete a specific product, when I am pressing the delete button it is deleting my products which is a document but it does not delete the corresponding image from Firebase Storage.
I have tried some way but it's not working, it's just deleting my Cloud Firestore document but the photo remains in Firebase Storage.
I am using the image URL to show the photo. I want that when I click on my delete Button it also delete the corresponding image from Firebase Storage. so I am using this to delete my Cloud Firestore document.
TextButton(
onPressed: () async {
await FirebaseFirestore.instance
.collection('users')
.doc(LoginUser!.uid)
.collection('products')
.doc(document.id)
.delete()
.then((value) async {
//await FirebaseStorage.instance.ref().child('productImage').child('productImageUrl').delete();
print(
'Product Deleted But image is still there in Storage Folder');
});
},
child: Text('Delete')),
I am using This code to save my image Url in Cloud Firestore
final productImgRef = FirebaseStorage.instance
.ref()
.child('productImage')
.child(FirebaseUser.uid +time +'.jpg');
await productImgRef.putFile(pickImageFile!);
var productImageUrl = await productImgRef.getDownloadURL();
await FirebaseFirestore.instance
.collection('users')
.doc(FirebaseUser.uid)
.collection('products')
.add({
'productName': _productName,
'productDes': _productDes,
'bidPrice': _bidPrice,
'auctionDate': _auctionDate,
'submitBy': userName,
'productImageUrl': productImageUrl,
});
Upvotes: 0
Views: 202
Reputation: 598765
Assuming that this commented out line is what you tried:
await FirebaseStorage.instance.ref().child('productImage').child('productImageUrl').delete();
The quotes around 'productImageUrl'
are a mistake there. With this code it tries to delete the image named productImageUrl
, which is not what your image is called.
That the very least it should be:
await FirebaseStorage.instance.ref().child('productImage').child(productImageUrl).delete();
By removing the quotes from around productImageUrl
, the code will use the value of the variable.
But more likely the productImageUrl
contains a download URL, in which case your first need to map that back to a Storage Reference
by calling the refFromURL
method:
var storageRef = FirebaseStorage.instance.refFromURL(productImageUrl);
await storageRef.delete();
Upvotes: 1