How to Delete a Firebase Storage File With Flutter

How to Delete a Firebase Storage File With Flutter?

Earlier we have been through Step By Step Guide to Implement Firebase with Flutter. when we use Firebase to store data from the Application so in this article We will go through How to Delete a Firebase Storage File With Flutter?

Learn how to efficiently delete a Firebase Storage file with Flutter in this insightful blog post. Discover step-by-step instructions and code snippets that demonstrate the process of deleting files from Firebase Storage using Flutter. Streamline your app’s storage management and ensure a seamless user experience by mastering the techniques explained in this tutorial. Level up your Flutter skills and handle file deletion effortlessly with Firebase Storage integration.

How to Delete a Firebase Storage File With Flutter?

On Android, you can call getReferenceForUrl() to get a StorageReference from a download URL, and a similar method exists on iOS.

But I can’t find a corresponding method in the FlutterFire reference docs. This unfortunately means that there is no way to map from a download URL back to a StorageReference in Flutter.

Change filePath to

String filePath = 'https://firebasestorage.googleapis.com/v0/b/dial-in-21c50.appspot.com/o/default_images%2Fuser.png?alt=media&token=c2ccceec-8d24-42fe-b5c0-c987733ac8ae'
                  .replaceAll(new 
                  RegExp(r'https://firebasestorage.googleapis.com/v0/b/dial-in-21c50.appspot.com/o/default_images%2F'), '').split('?')[0];

FirebaseStorage.instance.ref().child(filePath).delete().then((_) => print('Successfully deleted $filePath storage item' ));

You can try with the below code snippet:

import 'package:path/path.dart' as Path;
  Future<void> deleteImage(String imageFileUrl) async {
  var fileUrl = Uri.decodeFull(Path.basename(imageFileUrl)).replaceAll(new RegExp(r'(\?alt).*'), '');


final StorageReference firebaseStorageRef =
    FirebaseStorage.instance.ref().child(fileUrl);
    await firebaseStorageRef.delete();
 }

Code snippet to delete the file from Firebase Storage with reference to the URL:

  if (oldUrl != null) {
  var fileUrl = Uri.decodeFull(Path.basename(oldUrl))
      .replaceAll(new RegExp(r'(\?alt).*'), '');
  StorageReference photoRef = await FirebaseStorage.instance
      .ref()
      .getStorage()
      .getReferenceFromUrl(oldUrl);
  try {
    await photoRef.delete();
  } catch (e) {}
}

The complete method will have a code snippet like the below:

Future<UserItem> uploadUserImage(String filePath, {String oldUrl}) async {
 if (oldUrl != null) {
  var fileUrl = Uri.decodeFull(Path.basename(oldUrl))
      .replaceAll(new RegExp(r'(\?alt).*'), '');
  StorageReference photoRef = await FirebaseStorage.instance
      .ref()
      .getStorage()
      .getReferenceFromUrl(oldUrl);
  try {
    await photoRef.delete();
  } catch (e) {}
}

Im.Image image = Im.decodeImage(File(filePath).readAsBytesSync());

// todo cleanup string formation
final StorageReference storageReference =
    FirebaseStorage().ref().child('user_images').child(
          DateTime.now().millisecondsSinceEpoch.toString() +
              '.' +
              filePath.split(".")[1],
        );
final StorageUploadTask uploadTask = storageReference.putFile(
  File(filePath),
);

/// wait for upload to complete
await uploadTask.onComplete;

/// get the uploaded items url
String url = await (storageReference.getDownloadURL());

/// add the pic to FireStore Instance
FirebaseUser user = await FirebaseAuth.instance.currentUser();
String token = user.uid;

/// adds the item to the corresponding token path
await _fireStore
    .document('$token')
    .setData({'userImage': url}, merge: true);

return await getUserData();
}

This function works very well for the firebase storage link:

static Future<bool> deleteFileFromFirebaseByUrl(String urlFile) async {
String fileName = urlFile.replaceAll("/o/", "*");
fileName = fileName.replaceAll("?", "*");
fileName = fileName.split("*")[1];
print(fileName);
StorageReference storageReferance = FirebaseStorage.instance.ref();
storageReferance
    .child(fileName)
    .delete()
    .then((_) => print('Successfully deleted $fileName storage item')); }

Conclusion:

Thanks for being with us on a Flutter Journey!!!

In this article, we have been through how to delete a firebase storage file with flutter.

Do let us know if you need any assistance with flutter development. We would love to assist you.

FlutterAgency.com is our portal Platform dedicated to Flutter Technology and Flutter Developers. The portal is full of cool resources from Flutter like Flutter Widget GuideFlutter ProjectsCode libs and etc.

FlutterAgency.com is one of the most popular online portals dedicated to Flutter Technology and daily thousands of unique visitors come to this portal to enhance their knowledge of Flutter.

Abhishek Dhanani

Written by Abhishek Dhanani

Abhishek Dhanani, a skilled software developer with 3+ years of experience, masters Dart, JavaScript, TypeScript, and frameworks like Flutter and NodeJS. Proficient in MySQL, Firebase, and cloud platforms AWS and GCP, he delivers innovative digital solutions.

Leave a comment

Your email address will not be published. Required fields are marked *

Discuss Your Project

Connect with Flutter Agency's proficient skilled team for your app development projects across different technologies. We'd love to hear from you! Fill out the form below to discuss your project.

Have Project For Us

Get in Touch

"*" indicates required fields

ready to get started?

Fill out the form below and we will be in touch soon!

"*" indicates required fields