0

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://')

Firestore Collection

2
  • 1
    It looks like there's a problem reading the URL. What does it show if you print(newsDataModel.get('fileUrl')) right before you use it? Commented Nov 24, 2021 at 15:07
  • You can check this link - stackoverflow.com/questions/54170250/… Commented Nov 24, 2021 at 16:17

1 Answer 1

1

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);
             }
      },
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.