将 futures 与 flutter maps 结合使用

using futures with flutter maps

我有这段代码应该循环遍历图像以将它们上传到 firebase,然后将它们的 link 放入产品 class 中,这样产品就可以拥有它的图像 link。然后,也上传产品。 问题是它不会等待上传发生以将其 link 插入到产品中。 代码

 List<String> imgUrls = [];
 Future<void> loopThroughMap()async{
_map.forEach((storedImage, inGallery) async {
  if (!inGallery && storedImage != null && storedImage.path != null) {
    await GallerySaver.saveImage(storedImage.path);
  }

  String urlString = await FirestoreHelper.uploadImage(storedImage);
  imgUrls.add(urlString);
});

}

这里调用了这个函数

`
    await loopThroughMap();
    print('FINISHED THIS ONE, imgs Urls length ${imgUrls.length}');
    for (int i = 0; i < imgUrls.length; i++) {
    if (i == 0)
    _editedProduct.imageUrl = imgUrls[i];
    else if (i == 1)
    _editedProduct.imageUrl2 = imgUrls[i];
    else if (i == 2)
    _editedProduct.imageUrl3 = imgUrls[i];
    else if (i == 3) _editedProduct.imageUrl4 = imgUrls[i];
    }`

imgUrls 列表长度始终为零。 会不会是map.foreach的问题?

好的,我将上传从 ForEach 循环更改为 for 循环,它工作正常!

List<File> _listedImages = [];
  Future<void> loopThroughMap(){
    _map.forEach((storedImage, inGallery) async {
      if (!inGallery && storedImage != null && storedImage.path != null) {
        GallerySaver.saveImage(storedImage.path);
      }

      _listedImages.add(storedImage);
    });
  }

/////

for(var img in _listedImages){
              String url = await FirestoreHelper.uploadImage(img);
              imgUrls.add(url);
            }

经过多次迭代,导致错误的唯一变量是 ForEach 循环。