Overview

A for loop is a control structure which can repeatly execute operations.

Standard for loop

The standard for loop has the following structure:

for (start; condition; step) {
    statements
}

‘start’ is called once at the beginng of the loop. The condition is called every loop cycle and the loop is stops when the condition does not hold.
‘step’ is a statement called after every loop cycle.

An example looks like:

for (var i = 0; i < 10; i++) {
  doSomething();
}

This loop would cycle ten times.

The statements in a for loop are all optional. So this would be a valid for loop which will run endless.

for ( ; ; ) {
  doSomething();
}

For in loop

The for in loop is used to run through all items of a Iterable. The syntax looks like the following:

for (var item in iterable) {
  doSomething(item);
}

The equivalent standard for loop would look like:

for (var i = 0; i < iterable.length; i++) {
  var item = iterable[i];
  doSomething(item);
}

Labeled for loop

Loops can also be labeled like in other languages such as Java. The label can than be used to break or continue the loop.

for (var i = 0; i < 10; i++) {
  for (var j = 0; j < 15; j++) {
    if ( j + i == 20) {
      // This will break the inner for loop.  
      break;
    }
  }
}

If you want to break the outer for loop you can do it by using a label:

outer: for (var i = 0; i < 10; i++) {
  for (var j = 0; j < 15; j++) {
    if ( j + i == 20) {
      // This will break the outer for loop.  
      break outer;
    }
  }
}

Iterable.forEach

In Dart the Iterable interface provides also a function called 'forEach' which takes a void Function(item) as argument.
This method also runs over all items in the iterable and calls the passed Function for all items.

The syntax looks like the following:

iterable.forEach((item) => doSomething());

The implementation of the forEach method just uses a for in loop:

  void forEach(void f(E element)) {
    for (E element in this) f(element);
  }