For in Dart

Dart provides several ways to create loops. Here are some basic types of loops in Dart.

void main() {
  // The most basic type, with a single condition.
  var i = 1;
  while (i <= 3) {
    print(i);
    i = i + 1;
  }

  // A classic initial/condition/after for loop.
  for (var j = 0; j < 3; j++) {
    print(j);
  }

  // In Dart, we use the `for-in` loop to iterate over a range of numbers.
  for (var i in Iterable<int>.generate(3)) {
    print('range $i');
  }

  // While loop without a condition will loop repeatedly
  // until you break out of the loop or return from
  // the enclosing function.
  while (true) {
    print('loop');
    break;
  }

  // You can also continue to the next iteration of the loop.
  for (var n in Iterable<int>.generate(6)) {
    if (n % 2 == 0) {
      continue;
    }
    print(n);
  }
}

To run the program, save it as for_loops.dart and use the dart command:

$ dart run for_loops.dart
1
2
3
0
1
2
range 0
range 1
range 2
loop
1
3
5

In Dart, we use while loops for the most basic type of loop with a single condition. The classic C-style for loop is also available.

Instead of using range like in some other languages, Dart uses the for-in loop to iterate over collections or ranges. To create a range of numbers, we use Iterable<int>.generate().

Dart doesn’t have an exact equivalent to a for loop without a condition, but we can achieve the same result with a while (true) loop and use break to exit.

The continue statement works the same way as in many other languages, allowing you to skip to the next iteration of the loop.

We’ll see some other loop forms later when we look at for-in statements with collections and other data structures.