4.5 C
New York
Friday, December 9, 2022

Dart: Using Async and Await in Loops

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:Advertisements

// 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.

Advertisements

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles