Dart – Loops

A looping statement in Dart or any other programming language is used to repeat a particular set of commands until certain conditions are not completed. There are different ways to do so. They are: 
 

  • for loop
  • for… in loop
  • for each loop
  • while loop
  • do-while loop

for loop

For loop in Dart is similar to that in Java and also the flow of execution is the same as that in Java.
Syntax: 

 for(initialization; condition; text expression){
    // Body of the loop
}

Control flow: 

Control flow goes as: 

  1. initialization
  2. Condition
  3. Body of loop
  4. Test expression

The first is executed only once i.e in the beginning while the other three are executed until the condition turns out to be false.
Example: 
 

Dart




// Printing w3wiki 5 times
void main()
{
    for (int i = 0; i < 5; i++) {
        print('w3wiki');
    }
}


Output: 
 

w3wiki
w3wiki
w3wiki
w3wiki
w3wiki

 

for…in loop

For…in loop in Dart takes an expression or object as an iterator. It is similar to that in Java and its execution flow is also the same as that in Java.
 

Syntax: 

 for (var in expression) {
   // Body of loop
}

Example: 
 

Dart




void main()
{
    var w3wiki = [ 1, 2, 3, 4, 5 ];
    for (int i in w3wiki) {
        print(i);
    }
}


Output: 
 

1
2
3
4
5

for each … loop

The for-each loop iterates over all elements in some container/collectible and passes the elements to some specific function.

Syntax:

 collection.foreach(void f(value))

Parameters:

  • f( value): It is used to make a call to the f function for each element in the collection.

Dart




void main() {
  var w3wiki = [1,2,3,4,5];
  w3wiki.forEach((var num)=> print(num));
}


Output:

1
2
3
4
5

while loop

The body of the loop will run until and unless the condition is true.
 

Syntax: 

 while(condition){
    text expression;
    // Body of loop
}

Example: 
 

Dart




void main()
{
    var w3wiki = 4;
    int i = 1;
    while (i <= w3wiki) {
        print('Hello Geek');
        i++;
    }
}


Output: 
 

Hello Geek
Hello Geek
Hello Geek
Hello Geek

 

do..while loop

The body of the loop will be executed first and then the condition is tested.
 

Syntax: 

 do{
    text expression;
    // Body of loop
}while(condition);

Example: 
 

Dart




void main()
{
    var w3wiki = 4;
    int i = 1;
    do {
        print('Hello Geek');
        i++;
    } while (i <= w3wiki);
}


Output: 
 

Hello Geek
Hello Geek
Hello Geek
Hello Geek

 



Contact Us