颤抖等待条件实现,然后再继续其余代码

时间:2019-08-18 20:54:59

标签: flutter dart

在继续其余代码之前,我需要异步函数等待某些表达式验证(例如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才能继续执行? 谢谢

3 个答案:

答案 0 :(得分:4)

你可以这样做。

Future<void> _waitUntilDone() async {
    final completer = Completer();
    if (_loading) {
      await 200.milliseconds.delay();
      return _waitUntilDone();
    } else {
      completer.complete();
    }
    return completer.future;
  }

甚至更好

var completer;

Future<void> _waitUntilDone() async {
  completer = Completer();
  return completer.complete();
}

void done() {
  if (completer)
    completer.complete();
}

在完全调用时,我们也可以发出一些值。

答案 1 :(得分:1)

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

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

答案 2 :(得分:0)

像这样吗?

delayed() async {
  await Future.delayed(Duration(seconds: 2));// or some time consuming call
  return true;
}

somefn() async{
    var x = await delayed();
    print(x);// gives true
}
somefn();