androidflutterdartmobilegoogle-cloud-storage

How do I loop through a list of files to write to local storage?


Future<void> downloadFiles(url) async {
var result = await getDirectories(url); //this function just returns the path in firestore storage

Directory appDocDir = await getApplicationDocumentsDirectory();
result.items.forEach((firebase_storage.Reference ref) async {
  File downloadToFile = File('${appDocDir.path}/notes/${ref.name}');
  try {
    await firebase_storage.FirebaseStorage.instance
        .ref(ref.fullPath)
        .writeToFile(downloadToFile);
  } on firebase_core.FirebaseException catch (e) {
    print(e);
  }
});

}

I made this function in flutter to loop through the files in my firebase cloud storage. I have tried writing to local storage with a single file and it works however when I loop through a list of files to write on local storage it doesn't work, it doesn't even produce an error, the code just stops at "foreach" it doesn't even execute the try catch block. Is there a specific function in flutter that writes multiple files to local storage?


Solution

  • its because you are using a forEach loop , you will have to use for Loop for the your code as below and it will work.

    Asynchronous methods doesnt work inside forEach Loop

    
        Future<void> downloadFiles(url) async {
                var result = await getDirectories(url); //this function just returns the path in firestore storage
                
                Directory appDocDir = await getApplicationDocumentsDirectory();
                for(int i = 0; i<result.items.length ; i++){
                      File downloadToFile = File('${appDocDir.path}/notes/${result.item[i].name}');
                      try {
                        await firebase_storage.FirebaseStorage.instance
                            .ref(ref.fullPath)
                            .writeToFile(downloadToFile);
                      } on firebase_core.FirebaseException catch (e) {
                        print(e);
                      }
                }
                }