如何遍历文件列表以写入本地存储?

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);
  }
});

}

我在 flutter 中创建了这个函数来循环访问我的 firebase 云存储中的文件。我曾尝试使用单个文件写入本地存储并且它可以工作但是当我循环遍历要写入本地存储的文件列表时它不起作用,它甚至不会产生错误,代码只是停止在“foreach " 它甚至不执行 try catch 块。 flutter中有没有专门写多个文件到本地的函数?

这是因为您使用的是 forEach 循环,您必须使用 for 循环来编写您的代码,如下所示,它会起作用。

异步方法在forEach循环

中不起作用

    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);
                  }
            }
            }