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:
for
loopfor...in
loopfor each
loopwhile
loopdo-while
loopfor
loopIn 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
}
// Using for loop to print out elements in the list void main() { var shots = ['Loops', 'in', 'Dart', 'Programming']; for (int i = 0; i < shots.length; i++){ print(shots[i]); } }
for...in
loopThe 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
}
// Using for...in loop to print out elements in the list void main() { var shots = ['for', 'in', 'loop', 'in', 'Dart', 'Programming']; for (var i in shots){ print(i); } }
for each
loopThe 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))
// Using forEachloop to print out elements in the list void main() { var num = [1, 2, 3, 4, 5, 6]; num.forEach((var item){ if(item %2 == 0){ //checks for even numbers in num list var myList = [item]; print(myList); //print even numbers } }); }
while
loopThe while
loop iterates a block of codes until the condition is false.
Syntax:
while(condition){
statement;
//Body of the loop
}
// Using while loop void main() { var shots = 3; int i=1; while (i <= shots){ //executes three times print('Shot: Loop in Dart programming'); i++; } print('Educative.io shot'); //execute onces }
do..while
loopThe 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);
// Using do...while loop void main() { var shots = 3; int i=1; do { //execute atleast once whether the condition is true or not print('Educative.io shot'); i++; } while (i == shots); //condition is false }
RELATED TAGS
CONTRIBUTOR
View all Courses