等待异步 forEach 完成所有迭代,然后在 Dart 中收集数据

Awaiting for an async forEach to finish all iterations then collect the data in Dart

我需要将 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 等待循环完成,然后再移动到循环后的下一个语句。像这个答案所暗示的那样延迟 is just a hack, not a solution. And this other answer does not really answer the question: .

像这样替换你的迭代语句

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);
  }
}