How to Delete a Firebase Storage File With Flutter ??

· 4 min read
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 ??

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.

Leave a Reply