Dart: Using Async and Await in Loops

Last updated on April 20, 2022 Pennywise Loading... Post a comment

In Dart (and Flutter as well), you can perform synchronous operations sequentially in loops by using Future.forEach. The example program below will print the numbers from 1 to 10. Every time it finishes printing a number, it will wait for 3 seconds before printing the next number.

// kindacode.com
void main() async {
  final items = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
  await Future.forEach(items, (item) async {
    print(item);
    await Future.delayed(const Duration(seconds: 3));
  });
}

An alternative way is to use for … in syntax, like this:

// kindacode.com
void main() async {
  final items = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
  for (int item in items) {
    print(item);
    await Future.delayed(const Duration(seconds: 3));
  }
}

Further reading:

You can also check out our Flutter category page or Dart category page for the latest tutorials and examples.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

You May Also Like