Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/dart/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Flutter 颤振:为什么代码执行不是';t暂停使用wait on Future_Flutter_Dart - Fatal编程技术网

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