Dart Loop is used to run a block of code repetitively for a given variety of times or until matches the specified situation. Loops are important tools for any programming language. A loop represents a set of instructions that should be repeated. In a loop’s context, a repetition is termed as an iteration.

A loop can have two elements – a body of the loop and control statements. The primary goal of the loop is to run the code multiple times. There are different types of loop in Dart.

List of Dart Loop

  • For Loop
  • For Each Loop
  • While Loop
  • Do While Loop

For Loop in Dart

The for loop is used when we know how many times a block of code will execute. The loop iteration starts from the initial value. It executes only once. The syntax of for loop is:

for(initialization; condition; increment/decrement){
            statements;
}

Example:

void main() {
  for (int i = 1; i <= 10; i++) {
    print(i);
  }
}

For Each Loop in Dart

The for each loop iterates over all list elements or variables. It is useful when you want to loop through list/collection. The syntax of for-each loop is:

collection.forEach(void f(value));

Example:

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

Also Read: How to Customize Flutter Packages to Suit Your Needs

While Loop in Dart

In while loop, the loop’s body will run until and unless the condition is true. You must write conditions first before statements. 

while(condition) {  
   // loop body  
}  

Example

void main() {
  int i = 1;
  while (i <= 10) {
    print(i);
    i++;
  }
}

Do While Loop in Dart

The do…while loop is similar to the while loop but only difference is that, first it executes the loop statement and then check the given condition. The syntax is given below.

do {  
    // loop body  
} while(condition);  

Example

void main() {
  int i = 1;
  do {
    print(i);
    i++;
  } while (i <= 10);
}

Leave Your Comment