gpt4 book ai didi

flutter 等待条件满足,然后再继续执行其余代码

转载 作者:行者123 更新时间:2023-12-03 02:42:19 26 4
gpt4 key购买 nike

在继续其余代码之前,我需要异步函数等待某些表达式验证(例如x == true)。

现在我正在像这样使用while循环

var x = false;

someFunction() async {

// here I want to await for
// as long as it takes for x to become true

while(!x) {
await new Future.delayed(new Duration(milliseconds: 250));
}

// i put 250 millisecond intentional delay
// to protect process from blocking.
// x is to be set true by external function
// rest of code ...
}

await someFunction();

您是否认为有更好的方法等待x更改为true才能继续执行?
谢谢

最佳答案

您可以使用三种方式进行异步/等待:-

void method1(){
List<String> myArray = <String>['a','b','c'];
print('before loop');
myArray.forEach((String value) async {
await delayedPrint(value);
});
print('end of loop');
}

void method2() async {
List<String> myArray = <String>['a','b','c'];
print('before loop');
for(int i=0; i<myArray.length; i++) {
await delayedPrint(myArray[i]);
}
print('end of loop');
}

Future<void> delayedPrint(String value) async {
await Future.delayed(Duration(seconds: 1));
print('delayedPrint: $value');
}

关于 flutter 等待条件满足,然后再继续执行其余代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57548302/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com