What are loops in Dart programming?
A loop is used in Dart or any other programming language to repeat a sequence of commands a given number of times or until it satisfies a condition.
It is convenient for iterating over a collection/list of items or repeating an operation.
The following are loops used in Dart programming:
forloopfor...inloopfor eachloopwhileloopdo-whileloop
Types of loops
for loop
In Dart, the for loop is the same as in C or Java. It runs a code block a certain number of times.
A for loop assigns an initial value to a variable as an iterator. It then iterates through the loop body as long as the given condition is true.
Syntax:
for(initialization; condition; express){
//Body of the loop
}
Code
// Using for loop to print out elements in the listvoid main(){var shots = ['Loops', 'in', 'Dart', 'Programming'];for (int i = 0; i < shots.length; i++){print(shots[i]);}}
for...in loop
The for in loop uses an expression or object as an iterator to loop through the elements one by one in order.
Syntax:
for (var in expr) {
//Body of the loop
}
Code
// Using for...in loop to print out elements in the listvoid main(){var shots = ['for', 'in', 'loop', 'in', 'Dart', 'Programming'];for (var i in shots){print(i);}}
for each loop
The for each loop iterates over all the elements in some collectible and passes the elements to some specific function.
Syntax:
iterable.foreach(void func(value))
Code
// Using forEachloop to print out elements in the listvoid main(){var num = [1, 2, 3, 4, 5, 6];num.forEach((var item){if(item %2 == 0){ //checks for even numbers in num listvar myList = [item];print(myList); //print even numbers}});}
while loop
The while loop iterates a block of codes until the condition is false.
Syntax:
while(condition){
statement;
//Body of the loop
}
Code
// Using while loopvoid main(){var shots = 3;int i=1;while (i <= shots){//executes three timesprint('Shot: Loop in Dart programming');i++;}print('Educative.io shot'); //execute onces}
do..while loop
The do..while loop executes the loop’s body at least once whether or not the condition is true.
Syntax:
do{
statement;
//Body of the loop
}while(condition);
Code
// Using do...while loopvoid main(){var shots = 3;int i=1;do {//execute atleast once whether the condition is true or notprint('Educative.io shot');i++;} while (i == shots); //condition is false}