Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

loops
dart
communitycreator

What are loops in Dart programming?

Maria Elijah

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:

  1. for loop
  2. for...in loop
  3. for each loop
  4. while loop
  5. do-while loop

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 list
void 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 list

void 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 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 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 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 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 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

loops
dart
communitycreator
RELATED COURSES

View all Courses

Keep Exploring