Home > other >  Firebase Storage Resource Not Downloading in Flutter App
Firebase Storage Resource Not Downloading in Flutter App

Time:12-29

I am attempting to download a .mp3 from my Firebase Cloud Storage project per this documentation, but pressing the elevated button (Android emulator) does nothing. When I say nothing I mean nothing, the print statement I added immediately after calling getApplicationDocumentsDirectory() is never output to console. This simple code is verbatim from the Firebase docs, what am I missing? I've added permissions in AndroidManifest to allow INTERNET and WRITE_EXTERNAL_STORAGE.

  fs.FirebaseStorage storage = fs.FirebaseStorage.instance;

ElevatedButton(
              onPressed: () {
                Future<void> download() async {
                  Directory dir = await getApplicationDocumentsDirectory();
                  print("File downloading to : ${dir}");
                  File file = File(
                      '${dir.path}/track-title');

                  fs.DownloadTask task = storage
                      .ref(
                           'gs://project_name.appspot.com/track-title') 
                            // 'project_name/track-title' as shown in docs also does not work
                      .writeToFile(file);

                  task.snapshotEvents.listen((fs.TaskSnapshot snapshot) {
                    print('Task state: ${snapshot.state}');
                    print(
                        'Progress: ${(snapshot.bytesTransferred / snapshot.totalBytes) * 100} %');
                  }, one rror: (e) {
                    // The final snapshot is also available on the task via `.snapshot`,
                    // this can include 2 additional states, `TaskState.error` & `TaskState.canceled`
                    print(task.snapshot);

                    if (e.code == 'permission-denied') {
                      print(
                          'User does not have permission to upload to this reference.');
                    }
                  });
                }
              },
              child: Text("Track Title")),

CodePudding user response:

Your code defines a function called download, but you don't actually invoke that function anywhere.

To execute the code in the download function you defined, add download() right before the closing } of onPressed:

ElevatedButton(
  onPressed: () {
    Future<void> download() async {
      ...
        if (e.code == 'permission-denied') {
          print(
              'User does not have permission to upload to this reference.');
        }
      });
    }
    download(); //            
  • Related