ZetCode

Dart loops

last modified October 18, 2026

In this article we show how to create loops in Dart language. We create loops with for and while statements. In addition, we present the break and continue statements.

Loops

The for and while statements are used to create loops. The break and continue statements are used to alter the loop execution.

Loops are used to execute statements multiple times or to traverse containers.

Dart while loop

The while statement is a control flow statement that allows code to be executed repeatedly based on a given boolean condition.

This is the general form of the while loop:

while (expression) {
  statement;
}

The while keyword executes the statements inside the block enclosed by the curly brackets. The statements are executed each time the expression is evaluated to true.

main.dart
void main() {
  var i = 0;
  var sum = 0;

  while (i < 10) {
    i++;
    sum += i;
  }

  print(sum);
}

In the code example, we calculate the sum of the values from 1 to 10.

The while loop has three parts: initialization, testing, and updating. Each execution of the statement is called a cycle.

var i = 0;

We initiate the i variable. It is used as a counter.

while (i < 10) {
  ...
}

The expression inside the round brackets following the while keyword is the second phase: the testing. The statements in the body are executed until the expression is evaluated to false.

i++;

This is the last, third phase of the while loop: the updating. We increment the counter. Note that improper handling of the while loops may lead to endless cycles.

$ dart main.dart
55

Dart do-while loop

The do-while statement checks the condition after the body has been executed. Therefore, the body is always executed at least once.

main.dart
void main() {
  var i = 10;

  do {
    print('i = $i');
    i--;
  } while (i > 10);
}

The condition i > 10 is false from the start, yet the body runs once.

$ dart main.dart
i = 10

Dart classic for loop

The classic for loop was taken from the C programming language. A for loop has also three phases: initialization, condition and code block execution, and incrementation.

main.dart
void main() {
  var sum = 0;

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

  print(sum);
}

In this example, we sum values 0..9 and print the result to the console.

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

In the first phase, we initiate the counter i to zero. This phase is done only once. Next comes the condition i < 10. If the condition is met, the statement inside the for block is executed. In the third phase the counter is increased. Now we repeat the phases 2 and 3 until the condition is not met and the for loop is left. In our case, when the counter i is equal to 10, the for loop stops executing.

$ dart main.dart
45

Dart for loop List

A for loop can be used for traversal of containers such as lists or maps. From the length property of the list we get its size.

main.dart
void main() {
  final planets = [
    'Mercury',
    'Venus',
    'Earth',
    'Mars',
    'Jupiter',
    'Saturn',
    'Uranus',
    'Neptune'
  ];

  for (var i = 0; i < planets.length; i++) {
    print(planets[i]);
  }

  print('In reverse:');

  for (var i = planets.length - 1; i >= 0; i--) {
    print(planets[i]);
  }
}

We have a list holding the names of the planets in our Solar System. Using two for loops, we print the values in ascending and descending orders.

for (var i = 0; i < planets.length; i++) {
  print(planets[i]);
}

The lists are accessed by zero-based indexing. The first item has index 0. Therefore, the i variable is initialized to zero. The condition checks if the i variable is less than the length of the list. In the final phase, the i variable is incremented.

for (var i = planets.length - 1; i >= 0; i--) {
  print(planets[i]);
}

This for loop prints the elements of the list in reverse order. The i counter is initialized to the last index. Since the indexing is zero based, the last element has index list size - 1. The condition ensures that the counter is greater than or equal to zero (list indexes cannot be negative). In the third step, the i counter is decremented by one.

$ dart main.dart
Mercury
Venus
Earth
Mars
Jupiter
Saturn
Uranus
Neptune
In reverse:
Neptune
Uranus
Saturn
Jupiter
Mars
Earth
Venus
Mercury

Dart for loop Map

A for loop can be used to traverse a Map.

main.dart
void main() {
  final fruit = {1: 'Apple', 2: 'Banana', 3: 'Cherry', 4: 'Orange'};

  for (final key in fruit.keys) {
    print(key);
  }

  for (final value in fruit.values) {
    print(value);
  }

  for (final entry in fruit.entries) {
    print('${entry.key}: ${entry.value}');
  }
}

In the example, we use for loops to print all keys, values, and map entries (key/value pairs).

for (final key in fruit.keys) {

In this for loop, we go through all map keys. The values property gives the values and entries gives key/value pairs.

$ dart main.dart
1
2
3
4
Apple
Banana
Cherry
Orange
1: Apple
2: Banana
3: Cherry
4: Orange

Dart for-in loop

The for-in loop simplifies traversing over collections of data. It has no explicit counter. It goes through the collection one by one and the current value is assigned to a variable defined in the construct. It works with any Iterable.

main.dart
void main() {
  final vals = [1, 2, 3, 4, 5];

  for (final e in vals) {
    print(e * e);
  }
}

In the example, we use for-in to go through a list of numbers.

for (final e in vals) {
  print(e * e);
}

We iterate through the list of numbers. The e is a temporary variable that contains the current value of the list. The loop goes through all the numbers and prints their squares to the console.

$ dart main.dart
1
4
9
16
25

Dart loop with index

The indexed property of an iterable yields records of an index and a value. Combined with a record pattern, it gives us both in a for-in loop.

main.dart
void main() {
  final words = ['sky', 'cup', 'rock'];

  for (final (i, word) in words.indexed) {
    print('$i: $word');
  }
}

The pattern (i, word) destructures each record into the index and the element.

$ dart main.dart
0: sky
1: cup
2: rock

Dart forEach

Iterables have the forEach method, which calls a function for each element. Unlike a loop, it cannot be interrupted with break or continue, and the callback cannot contain await that the loop would respect.

main.dart
void main() {
  final words = ['sky', 'cup', 'rock'];

  words.forEach(print);

  final ages = {'John': 34, 'Lucy': 28};
  ages.forEach((name, age) => print('$name is $age'));
}

We pass the print function directly to forEach. For maps, the callback receives the key and the value.

$ dart main.dart
sky
cup
rock
John is 34
Lucy is 28

Dart nested for loop

For statements can be nested; i.e. a for statement can be placed inside another for statement. All cycles of a nested for loop are executed for each cycle of the outer for loop.

main.dart
void main() {
  final a1 = ['A', 'B', 'C'];
  final a2 = ['A', 'B', 'C'];

  for (final x in a1) {
    for (final y in a2) {
      print('$x$y');
    }
  }
}

In this example, we create a Cartesian product of two lists.

for (final x in a1) {
  for (final y in a2) {
    print('$x$y');
  }
}

There is a nested for loop inside another parent for loop. The nested for loop is executed fully for each of the cycles of the parent for loop.

$ dart main.dart
AA
AB
AC
BA
BB
BC
CA
CB
CC

Dart collection for

A for can also appear inside a collection literal, where it generates elements. This is often a clearer alternative to map followed by toList.

main.dart
void main() {
  final squares = [for (var i = 1; i <= 5; i++) i * i];
  print(squares);

  final even = [
    for (var i = 1; i <= 10; i++)
      if (i.isEven) i
  ];
  print(even);
}

The first list is built from a loop; the second adds a collection if to filter the generated values.

$ dart main.dart
[1, 4, 9, 16, 25]
[2, 4, 6, 8, 10]

Dart break statement

The break statement can be used to terminate the execution of a loop created by while, do, and for statements.

main.dart
import 'dart:math';

void main() {
  const max = 30;
  final rnd = Random(7);

  while (true) {
    final value = rnd.nextInt(max);
    print(value);

    if (value == 22) {
      break;
    }
  }
}

We define an endless while loop. We use the break statement to get out of this loop. We choose a random value from 0 to 29 and print it. If the value equals 22, we finish the loop. The generator is seeded to make the output reproducible; without a seed, the output differs on each run.

$ dart main.dart
10
17
8
9
6
8
22

Dart continue statement

The continue statement is used to skip a part of the loop and continue with the next iteration of the loop. In the following example, we print the numbers from 1 to 20 that cannot be divided by 2 without a remainder.

main.dart
void main() {
  var num = 0;

  while (num < 20) {
    num++;

    if (num % 2 == 0) {
      continue;
    }

    print(num);
  }
}

We iterate through the numbers 1..20 with the while loop.

if (num % 2 == 0) {
  continue;
}

If the expression num % 2 returns 0, the number in question can be divided by 2. The continue statement is executed and the rest of the cycle is skipped. In our case, the last statement of the loop is skipped and the number is not printed to the console. The next iteration is started.

$ dart main.dart
1
3
5
7
9
11
13
15
17
19

Dart labeled loops

A label placed before a loop lets break and continue target that loop from inside a nested loop.

main.dart
void main() {
  outer:
  for (var i = 1; i <= 3; i++) {
    for (var j = 1; j <= 3; j++) {
      if (j == 2) continue outer;
      if (i == 3) break outer;
      print('i=$i, j=$j');
    }
  }
}

When j is 2, continue outer starts the next cycle of the outer loop; when i is 3, break outer terminates both loops.

$ dart main.dart
i=1, j=1
i=2, j=1

Source

Dart loops - language reference

In this article we have covered loops in Dart.

Author

My name is Jan Bodnar, and I am a passionate programmer with extensive programming experience. I have been writing programming articles since 2007. To date, I have authored over 1,400 articles and 8 e-books. I possess more than ten years of experience in teaching programming.

List all Dart tutorials.