【问题标题】:Awaiting for an async forEach to finish all iterations then collect the data in Dart等待异步 forEach 完成所有迭代,然后在 Dart 中收集数据
【发布时间】:2021-04-22 04:04:15
【问题描述】:

我需要将 3 个表的数据合并到一个块中:

getAll() async {
    List<MoveInProgramViewModel> filledList = [];
    final moveInProgramList = await moveInProgramRepository.getAllFromDb();
    moveInProgramList.forEach((mip) async {
      final move = await moveRepository.getFromDb(mip.moveID);
      final program = await programRepository.getFromDb(mip.programID);
      filledList.add(MoveInProgramViewModel(
        mip.id,
        move,
        program,
        mip.indexInProgram,
        mip.sets,
        mip.createdDate,
        mip.modifiedDate,
      ));
      controller.add(filledList);
    });
  }

请注意,我在每个循环中都调用 controller.add(filledList);。我更喜欢把它放在循环之外,只有在所有数据都被填充后才被调用,但结果是一个空列表被添加到流中。可能有一个await 或一个阻塞Future 等待循环完成,然后再移动到循环之后的下一条语句。像这个答案所暗示的延迟https://stackoverflow.com/a/62734808/4854670 只是一个黑客,而不是一个解决方案。而这个其他答案并没有真正回答这个问题:https://stackoverflow.com/a/58562342/4854670

【问题讨论】:

    标签: flutter dart stream-builder


    【解决方案1】:

    像这样替换你的迭代语句

    getAll() async {
      List<MoveInProgramViewModel> filledList = [];
      final moveInProgramList = await moveInProgramRepository.getAllFromDb();
      for (final mip in moveInProgramList) {
        final move = await moveRepository.getFromDb(mip.moveID);
        final program = await programRepository.getFromDb(mip.programID);
        filledList.add(MoveInProgramViewModel(
          mip.id,
          move,
          program,
          mip.indexInProgram,
          mip.sets,
          mip.createdDate,
          mip.modifiedDate,
        ));
        controller.add(filledList);
      }
    }
    

    【讨论】:

    • 使用简单的for 循环允许我们将controller.add(filledList); 移出循环并且它按预期工作。
    猜你喜欢
    • 2019-11-29
    • 1970-01-01
    • 1970-01-01
    • 2019-06-28
    • 2023-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多