Flutter 等待异步forEach完成所有迭代,然后在Dart中收集数据
我需要将3个表的数据组合成一个整体:Flutter 等待异步forEach完成所有迭代,然后在Dart中收集数据,flutter,dart,stream-builder,Flutter,Dart,Stream Builder,我需要将3个表的数据组合成一个整体: getAll() async { List<MoveInProgramViewModel> filledList = []; final moveInProgramList = await moveInProgramRepository.getAllFromDb(); moveInProgramList.forEach((mip) async { final move = await moveRepositor
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.addFilled列表;在每个循环中。我更喜欢将其放在循环之外,以便仅在填充所有数据后调用,但结果是,将一个空列表添加到流中。可能存在等待或阻塞未来,等待循环完成,然后再移动到循环后的下一个语句。像这个答案所暗示的那样的拖延只是一种手段,而不是解决办法。而另一个答案并不能真正回答这个问题:。像这样替换您的迭代语句
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.addFilled列表;脱离循环,并按预期工作。