【问题标题】:How do I wait for an async function to complete within a condition?如何等待异步函数在条件内完成?
【发布时间】:2020-12-03 10:37:29
【问题描述】:

我有一个 IF 条件,其中包含异步代码。我想在继续执行其他代码之前等待条件内的过程完成。如何做到这一点?我的代码如下:

  List<String> imageURLs = [];
  if (images.length > 0) {
    images.forEach((element) async  {
      String imageURL = await savePostImage(element);
      imageURLs.add(imageURL);
    });
  } //This should complete
  data.addAll({'images': imageURLs}); /For this to be executed

【问题讨论】:

    标签: flutter asynchronous dart async-await


    【解决方案1】:

    使用Future.forEach

    await Future.forEach(images, (element) {
      // Your logic ...
    });
    

    【讨论】:

    • 或者普通的for循环。
    猜你喜欢
    • 1970-01-01
    • 2019-06-16
    • 1970-01-01
    • 2019-11-29
    • 2023-03-10
    • 2019-05-17
    • 2020-07-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多