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?


Solution 1: Kaushik Chandru

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


Solution 2: 无夜之星辰

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


Solution 3: stacktrace2234

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

enter image description here