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?
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
Timer.run
to Future.delayed
, however, Timer.run
did not return future. This is a very important difference between them and you can't ignore.
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);
}
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");
}
async
functions that youawait
. If you must use aTimer
, you can have theTimer
use aCompleter
and then you canawait
thatCompleter
'sFuture
before doingprint(3)
.Completer
can do the same likeSemaphore
in iOS.