Loops in Dart Programming

Dart ProgrammingServer Side ProgrammingProgramming

For loop is a type of definite loop in nature. There are mainly two types of loops that Dart provides us. Mainly these are −

  • For loop

  • For-in loop

We will explore both of these loops in the below post.

For loop

For loop in Dart follows a standard structure of the for loop that is present in C++ or Java. The structure of for loop in Dart looks something like this −

Syntax

for (initialization; condition; step) {
   // Statements
}

Example

Consider the example shown below -

 Live Demo

void main() {
   for (int i = 0; i < 5; i++) {
      print('TutorialsPoint : ${i + 1}');
   }
}

In the above example, we have a for loop that starts looping from i = 0 and it will run until the condition ( i < 5 ) is true, and it increments (i) by one at every iteration, and at each iteration, we are simply printing the statement written inside the print() function.

Output

TutorialsPoint : 1
TutorialsPoint : 2
TutorialsPoint : 3
TutorialsPoint : 4
TutorialsPoint : 5

For-in loop

The for-in loop is also a definite loop and follows like a python for-in loop syntax.

Syntax

for(var x in list/iterator){
   // statements
}

Example

Consider the example shown below −

 Live Demo

void main() {
   var fruits = ['apple','banana','kiwi','mango'];
   print(fruits);
   for( var fruit in fruits ){
      print("The current fruit is = $fruit");
   }
}

In the above example, we have an array named fruits and then we are looping through each of the fruits array element using the for-in loop and printing the statement present inside the print() function.

Output

[apple, banana, kiwi, mango]
The current fruit is = apple
The current fruit is = banana
The current fruit is = kiwi
The current fruit is = mango

It should also be noted that, unlike JavaScript, the variables that are present inside the for loops will not be hoisted. If we try to print fruit outside the for-in loop it will simply result in an error.

Example

Consider the example shown below −

void main() {
   var fruits = ['apple','banana','kiwi','mango'];
   print(fruits);
   for( var fruit in fruits ){
      print("The current fruit is = $fruit");
   }
   print(fruit);
}

Output

lib/main.dart:7:9:
Error: Getter not found: 'fruit'.
   print(fruit);
         ^^^^^
Error: Compilation failed.
raja
Published on 21-May-2021 13:06:08
Advertisements