【问题标题】:using futures with flutter maps使用带有颤振地图的期货
【发布时间】:2020-02-24 07:27:09
【问题描述】:

我有这段代码,它应该循环遍历图像以将它们上传到 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的问题?

【问题讨论】:

  • 编译器是否到达您的 if 语句?我也认为你应该删除第二个异步。
  • @P4yam 我认为这是 foeach 的问题!

标签: asynchronous flutter async-await future


【解决方案1】:

好的,我把上传从 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 循环。

【讨论】:

    猜你喜欢
    • 2021-01-26
    • 1970-01-01
    • 2019-12-12
    • 1970-01-01
    • 1970-01-01
    • 2018-10-01
    • 1970-01-01
    • 2020-07-19
    • 2021-05-30
    相关资源
    最近更新 更多