Qasem Zreaq
Qasem Zreaq

Reputation: 29

flutter delete an image from firebase storage

I need to delete an image from firebase storage. I have a function that uploads an image to firebase storage, but i don’t know how to delete image from firebase storage.

here is the function of upload an image

Future uploadImageToFirebase(BuildContext context,File file) async {
    String fileName = basename(file.path);
    StorageReference firebaseStorageRef =
    FirebaseStorage.instance.ref().child('uploads/$fileName');

    StorageUploadTask uploadTask = firebaseStorageRef.putFile(file);

    StorageTaskSnapshot taskSnapshot = await uploadTask.onComplete;
    taskSnapshot.ref.getDownloadURL().then(
            (value) {
          print(value);
          setState(() {
            widget.photoAssetPaths[visiblePhotoIndex] = value;
          });
        });
  }

can any one help me write a method to delete an image based on its url from the code?

Upvotes: 0

Views: 1869

Answers (3)

Xander Selorm
Xander Selorm

Reputation: 718

So this is quite simple to do. This is a simple function I wrote to delete my files from the storage bucket.

This is a simple method that takes the URL of the file to be deleted as a parameter:

deleteFile(url)

The next thing is to get the reference from the URL:

await FirebaseStorage.instance.refFromURL(url).delete();

Please note that this code is in a try-catch block so as to catch any unforeseen error.

Here's the complete code:

Future<void> deleteFile(String url) async {
  try {
    await FirebaseStorage.instance.refFromURL(url).delete();
  } catch (e) {
    print("Error deleting db from cloud: $e");
  }
}

Happy Coding!

Upvotes: 3

Frank van Puffelen
Frank van Puffelen

Reputation: 598765

Once you have a Reference to the file in Cloud Storage, you can call delete on that reference. To map a download URL to a reference, you can call storage.refFromUrl().

So, given the download URL, that should be something like:

FirebaseStorage.instance.refFromUrl(downloadUrl).delete();

Upvotes: 2

Kyle Noome
Kyle Noome

Reputation: 26

You can always just delete it from the firebase dashboard or do you want the user to be able to delete an image from a button or something?

Upvotes: 0

Related Questions