Code:
void _test() {
print(1);
Timer.run(() {
print(2);
});
print(3);
}
Print 1 3 2.
I want print 1 2 3.
In iOS I can use Semaphore, how can I do this in flutter?
CodePudding user response:
Awaiting for a method to complete can be written inside a future
void _test() async{
print(1);
Future.delayed(Duration(seconds : 0), (){
print(2);
});
print(3);
}
//Output 1 3 2
void _test() async{
print(1);
await Future.delayed(Duration(seconds : 0), (){
print(2);
});
print(3);
}
//Output 1 2 3
In the second example the await will wait for the future to complete and then move to the next task
CodePudding user response:
Timer.run()
basically tells the program that here is a piece of code that should be executed but I don't care if it finishes before it reaches the code outside of this block.
If you want to wait a bit, use Future.delayed
:
runAsyncMethod() async {
print("1");
await Future.delayed(Duration(seconds: 3), () {print("2");});
print("3");
}
CodePudding user response:
Thanks @jamesdlin, I solved with his comment, below is desired code:
void _test() async {
print(1);
Completer<void> completer = Completer();
Timer.run(() {
print(2);
completer.complete();
});
await completer.future;
print(3);
}