【问题标题】:How do I loop through a list of files to write to local storage?如何循环遍历要写入本地存储的文件列表?
【发布时间】:2021-06-27 16:08:46
【问题描述】:
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 中是否有将多个文件写入本地存储的特定功能?

【问题讨论】:

  • 您可能需要将 await 放在 results.items.forEach 之前
  • 试过了,报错。它是说“foreach”是“void”类型,所以它的值不能被使用

标签: android flutter dart mobile google-cloud-storage


【解决方案1】:

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

异步方法在 forEachLoop 中不起作用


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

【讨论】:

  • 我应用了这个,但它仍然没有工作看起来我的问题出在谷歌存储方面。我将发布一个新问题,问题不在 foreach 中
  • 可能是但不要在 forEach 循环中使用异步方法
猜你喜欢
  • 1970-01-01
  • 2016-05-07
  • 1970-01-01
  • 2023-03-20
  • 1970-01-01
  • 2012-04-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多