NewbieCoder
NewbieCoder

Reputation: 71

Async function of the Dart programming language is not working properly

I couldn't figure out why the following code didn't work correctly. I also tried it on DartPad. The result is the same.

import 'dart:async';

Future<bool> longWait(String prefix) async {
  for (int i = 0; i < 5; i++) {
    print('$prefix $i');
  }
  return true;
}

Future testAsync() async {
  print('starting');
  longWait('Async');
  print('done');
}

main(List<String> arguments) {
  testAsync();
}
the result is:
starting
Async 0
Async 1
Async 2
Async 3
Async 4
done

but it has to be this:
starting
done
Async 0
Async 1
Async 2
Async 3
Async 4

Upvotes: 2

Views: 41

Answers (1)

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 658067

Since Dart 2 sync code at the beginning of async functions is executed sync.
This was different in Dart 1.

A workaround would be

Future<bool> longWait(String prefix) async {
  await Future.microtask((){});

  for (int i = 0; i < 5; i++) {
    print('$prefix $i');
  }
  return true;
}

The code after the await is executed async and results in the desired behavior. (tested in DartPad)

Upvotes: 2

Related Questions