Reputation: 33
how can I get a button to delete a file from Firebase Storage using a URL as a reference. The URL is retrieved from a Firestore collection field called "fileUrl" using the Firebase Storage getDownloadUrl method. When I try to delete, I receive an error and my app crashes.
Code:
onPressed: () async {
if (newsDataModel.get('fileUrl') != null) {
await FirebaseStorage.instance.refFromURL(newsDataModel.get('fileUrl')).delete();
} else {
return;
}
await newsDataModel.reference.delete().then((value) => Navigator.pop(context));
}
Error:
_AssertionError ('package:firebase_storage/src/firebase_storage.dart':
Failed assertion: line 112 pos 12: 'url.startsWith('gs://') || url.startsWith('http')':
'a url must start with 'gs://' or 'https://')
Upvotes: 0
Views: 796
Reputation: 33
Realized that I had made a mistake. Some of the collections have fileUrl fields that are empty/null, so I was deleting collections that had null values and therefore returned an error.
New updated code:
onPressed: () async {
try {
if (hwDataModel.get('fileUrl') != null) {
await FirebaseStorage.instance.refFromURL(hwDataModel.get('fileUrl')).delete()
.then((value) => {
hwDataModel.reference.delete().then((value) =>
Navigator.pop(context))});
} else if (hwDataModel.get('fileUrl') == null) {
await hwDataModel.reference.delete().then(
(value) => Navigator.pop(context));
};
} on FirebaseException catch (error) {
Fluttertoast.showToast(
msg: error.message.toString(),
gravity: ToastGravity.TOP,
backgroundColor: Colors.red,
textColor: Colors.white);
}
},
Upvotes: 1