'Deleting a folder from Firebase Cloud Storage in Flutter
I have a Flutter mobile app in which I am trying to delete a folder (and its contents) from Firebase Cloud Storage. My method is as follows:
deleteFromFirebaseStorage() async {
return await FirebaseStorage.instance.ref().child('Parent folder/Child folder').delete();
}
I expect Child folder
and its contents to be deleted, but this exception is thrown:
Unhandled Exception: PlatformException(Error -13010, FIRStorageErrorDomain, Object Parent folder/Child folder does not exist.)
However I can clearly see that folder exists in Cloud Storage. How do I delete this folder?
Solution 1:[1]
Cloud Storage doesn't actually have any folders. There are just paths that look like folders, to help you think about how your structure your data. Each object can just have a common prefix that describes its "virtual location" in the bucket.
There's no operations exposed by the Firebase SDKs that make it easy to delete all objects in one of these common prefixes. Your only real option is to list all files in a common prefix, iterate the results, and delete each object individually.
Unfortunately, the list files API has not made it to flutter yet, as discussed here. So you are kind of out of luck as far as an easy solution is concerned. See also: FirebaseStorage: How to Delete Directory
Your primary viable options are:
- Keep track of each object in a database, then query the database to get the list of objects to delete.
- Delete the objects on a backend using one of the server SDKs. For example: Delete folder in Google Cloud Storage using nodejs gcloud api
Solution 2:[2]
Currently, I'm working on a project that contains a single file inside every folder so I did this and it worked for me.
await FirebaseStorage.instance.ref("path/" + to + "/" + folder)
.listAll().then((value) {
FirebaseStorage.instance.ref(value.items.first.fullPath).delete();
});
This code deletes the file and folder as well. Since, there's no folder here, deleting the file deletes the folder or reference. You can use foreach loop or map to delete everything from the folder if you have multiple files.
Solution 3:[3]
MD. Saffan Alvy was right, but to completely delete all and not just one file do this. if you didn't know.
await await FirebaseStorage.instance.ref("users/${FirebaseAuth.instance.currentUser!.uid}/media").listAll().then((value) {
value.items.forEach((element) {
FirebaseStorage.instance.ref(element.fullPath).delete();
);
});
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 | Doug Stevenson |
Solution 2 | MD. Saffan Alvy |
Solution 3 | PAGE BUNNII |