Hi Guy’s Welcome to Proto Coders Point. In this Flutter dart article, let’s checkout how to preform asynchronous operation in loops using async await and by using Future.forEach function.
Synchronous vs Asynchronous programming
- synchronous: In simple words, When you execute code synchronously then you need to wait for it to finish task 1 before you move to task 2.
- asynchronous: When you execute code asynchronously, then you can continue to execute the next task, no need to wait for the previous task to complete, but in case if task 1 & task 2 are related like, talk 2 get data from task 1 then you need to make use of async & await in a flutter.
Learn More about Flutter Future, Async & Await
Flutter await foreach – set duration between each loop iteration
Example 1: dart async for loops using Future.forEach function
The below code is a count down program, it will print numbers from 10 – 1 as listed in the array, After every print the program will wait for 1 second and then print the next iteration for the for loop.
In forEach loop I have make use of async await keywords to preform asynchronous operation with delay in loop.
// protocoderspoint.com void main() async { final items = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; Iterable inReverse = items.reversed; await Future.forEach(inReverse, (item) async { print(item); await Future.delayed(const Duration(seconds: 1)); // wait for 1 second before next iteration }); }
Example 2: using for in loop with async await
// protocoderspoint.com void main() async { final items = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; Iterable inReverse = items.reversed; for (int item in inReverse) { print(item); await Future.delayed(const Duration(seconds: 1)); } }
Recommended Flutter dart articles
Dart Calculate product/multiplication on 2 number.
Print pattern star, number, character in dart.