I need my async function to await for some expression to validate (ex. x == true) before continue with the rest of code.
right now I am using while loop like this
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();
do you think there is a better way to wait for x to change to true before continue with execution ? Thank you
See example below. Because await is only valid inside async functions and modules, which themselves are asynchronous and return promises, the await expression never blocks the main thread and only defers execution of code that actually depends on the result, i.e. anything after the await expression.
How do you wait seconds in flutter? Execute Code After 5 Seconds: Future. delayed(Duration(seconds: 5), (){ print("Executed after 5 seconds"); });
We put await in front of an asynchronous function to make the subsequence lines waiting for that future's result. We put async before the function body to mark that the function support await . An async function will automatically wrap the return value in Future if it doesn't already.
async: You can use the async keyword before a function's body to mark it as asynchronous. async function: An async function is a function labeled with the async keyword. await: You can use the await keyword to get the completed result of an asynchronous expression. The await keyword only works within an async function.
You could do something like this.
Future<void> _waitUntilDone() async {
final completer = Completer();
if (_loading) {
await 200.milliseconds.delay();
return _waitUntilDone();
} else {
completer.complete();
}
return completer.future;
}
or even better
var completer;
Future<void> _waitUntilDone() async {
completer = Completer();
return completer.complete();
}
void done() {
if (completer)
completer.complete();
}
at complete call, we can also emit some value as well.
You can use three way to async/await :-
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');
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With