Dart async execution order

Issue

I’m trying to understand proper execution order of async functions in Dart. Here is a code that puzzles me:

void main() async {
  print(1);
  f1();
  print(3);
}

void f1() async {
  print(2);
}

According to spec first main() will be executed then f1(). So I expect output:

1
3
2

However real output is:

1
2
3

Does it mean f1() is executed synchronously?

However if I add await Future.delayed(Duration.zero); to f1() before print the output is as I expect:

void main() async {
  print(1);
  f1();
  print(3);
}

void f1() async {
  await Future.delayed(Duration.zero);
  print(2);
}
1
3
2

Can anyone explain that?

Solution

Just adding the word async does not make a function asynchronous. If you mark a function that is fully synchronous async, it will execute as any other synchronous function/code would. When you add the Future.delayed, it makes the function actually asynchronous, which puts your print(2) in the event queue so that it’s executed later than print(3).

Answered By – Christopher Moore

Answer Checked By – Mary Flores (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *