1

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?

2
  • 1
    In general, prefer async functions that you await. If you must use a Timer, you can have the Timer use a Completer and then you can await that Completer's Future before doing print(3).
    – jamesdlin
    Aug 17, 2022 at 3:23
  • 1
    Thanks @jamesdlin. Completer can do the same like Semaphore in iOS. Aug 17, 2022 at 3:42

3 Answers 3

1

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

2
  • You changed 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. Aug 17, 2022 at 3:50
  • Yeah i agree timer.run and future are not same. But just wrote what's generally used to await an execution. Aug 17, 2022 at 3:52
1

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

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.