In this tutorial you will learn about the Dart Loops and its application with practical example.
Dart Loops
Loop statements are used to execute the block of code repeatedly for a specified number of times or until it meets a specified condition. Loop statement are very useful to iterate over collection/list of items or to perform a task for multiple times. In Dart, we have following loop statements available-
Dart for Loop
The for loop is used when we want to execute block of code known times. In Dart, basic for loop is similar as it is in C. The for loop takes a variable as iterator and assign it with an initial value, and iterate through the loop body as long as the test condition is true.
Syntax :-
1 2 3 |
for(Initialization; Condition; incr/decr){ // loop body } |
Example:-
1 2 3 4 5 6 |
void main() { print('W3Adda - Dart for Loop'); for (int ctr = 1; ctr <= 5; ctr++) { print(ctr); } } |
Output:-
Dart for..in Loop
The for in loop takes an expression or object as iterator, and iterate through the elements one at a time in sequence. The value of the element is bound to var, which is valid and available for the loop body. Once the loop statements are executed current iteration, the next element is fetched from the iterator, and we loop another time. When there is no more elements in iterator, the for loop is ended.
Syntax:-
1 2 3 |
for (var in expression) { // Statement(s) } |
Example:-
1 2 3 4 5 6 7 |
void main() { var counter = [11,12,13,14,15]; print('W3Adda - Dart for..in loop'); for (var ctr in counter) { print(ctr); } } |
Output:-
Dart While Loop
The while loop will execute a block of statement as long as a test expression is true.
Syntax:-
1 2 3 4 |
while(condition) { // loop body } |
Example:-
1 2 3 4 5 6 7 8 9 10 |
void main() { var ctr =1; var maxCtr =5; print("W3Adda - Dart while loop"); while(ctr<=maxCtr){ print(ctr); ctr = ctr+1; } } |
Output:-
Dart do…while Loop
The do…while statement executes loop statements and then test the condition for next iteration and executes next only if condition is true.
Syntax:-
1 2 3 |
do{ // loop body } while(condition); |
Example:-
1 2 3 4 5 6 7 8 9 10 11 |
void main() { var ctr =1; var maxCtr =5; print("W3Adda - Dart do while loop"); do{ print("Hello World! Value is :${ctr}"); ctr = ctr+1; }while(ctr<=maxCtr); } |
Output:-