Flutter 颤振:为什么代码执行不是';t暂停使用wait on Future
调用此方法:Flutter 颤振:为什么代码执行不是';t暂停使用wait on Future,flutter,dart,Flutter,Dart,调用此方法: void method() { List<String> items = ["A", "B", "C"]; print("Start of loop"); items.forEach((String value) async { print("Value = $value"); await Future.delayed(Duration(seconds:1), () => print("$value")); // why executi
void method() {
List<String> items = ["A", "B", "C"];
print("Start of loop");
items.forEach((String value) async {
print("Value = $value");
await Future.delayed(Duration(seconds:1), () => print("$value")); // why execution isn't paused here
});
print("End of loop");
}
预期输出:
Start of loop
Value = A
A
Value = B
B
Value = C
C
End of loop
注意:
Start of loop
Value = A
Value = B
Value = C
End of loop
A
B
C
我知道这可以通过使用
for
循环来实现,但是我想知道为什么在上面的代码中执行没有停止使用wait
问题在于List.forEach
不尊重/等待异步函数
当您查看的文档中的实现部分时,您会发现for循环并不等待执行的函数,因此不尊重任何异步函数,而是简单地执行它们,而不等待将来解析它们
您可以通过以下方式实现预期行为:
void方法()异步{
清单项目=[“A”、“B”、“C”];
打印(“循环开始”);
wait Future.forEach(项,(字符串值)异步{
打印(“值=$Value”);
等待未来。延迟(持续时间(秒:1),()=>打印($value));
});
打印(“循环结束”);
}
之所以发生这种情况,是因为将异步
函数与forEach
一起使用的等效功能如下:
void method() {
List<String> items = ["A", "B", "C"];
print("Start of loop");
for (String item in items) {
myAsyncFunction(item);
}
print("End of loop");
}
myAsyncFunction(String item) async {
print("Value = $item");
await someFuture;
}
void方法(){
清单项目=[“A”、“B”、“C”];
打印(“循环开始”);
for(项中的字符串项){
myAsyncFunction(项目);
}
打印(“循环结束”);
}
myAsyncFunction(字符串项)异步{
打印(“值=$item”);
等待未来;
}
如您所见,
myAsyncFunction
仍然是async
并使用wait
,但是method()中没有暂停。使用此替代代码,您可以选择使method()
异步并等待myAsyncFunction
,或者按照其他人的建议,您可以使用Future.forEach
。谢谢,但您能告诉我您从哪里找到列表。forEach不尊重/等待异步函数
?谢谢,但愿我能接受两个答案。这很有帮助!
void method() {
List<String> items = ["A", "B", "C"];
print("Start of loop");
for (String item in items) {
myAsyncFunction(item);
}
print("End of loop");
}
myAsyncFunction(String item) async {
print("Value = $item");
await someFuture;
}