使用带有波动图的期货

问题描述 投票:0回答:1

我有此代码,该代码应遍历图像以将其上传到firebase,然后将其链接放在Product类中,以便产品具有其图像链接。然后,也上传产品。问题在于它不等待上载发生而将其链接插入产品。代码

 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可能有问题吗?

asynchronous flutter async-await future
1个回答
0
投票

确定,我将上传从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循环。

© www.soinside.com 2019 - 2024. All rights reserved.