TExcelTAD
Home › Flutter › Dart Loops

Dart Loops

Loops repeat code. Dart offers the classic for loop, a for-in loop for collections, while and do-while loops, plus break and continue to control them. In Flutter you will also meet collection for, which builds lists of widgets inside the UI tree.

The classic for loop

A for loop has three parts: an initializer, a condition checked before each pass, and an update run after each pass.

dart · try it yourself
void main() {
  for (var i = 1; i <= 5; i++) {
    print('Step $i');
  }

  // counting down by two
  for (var i = 10; i > 0; i -= 2) {
    print(i);
  }
}
Step 1
Step 2
Step 3
Step 4
Step 5
10
8
6
4
2

for-in loops

When you just want every element of a list, set or other iterable, for-in is cleaner — no index to manage.

dart · try it yourself
void main() {
  var fruits = ['mango', 'lychee', 'durian'];
  for (final fruit in fruits) {
    print('I like $fruit');
  }

  var scores = {'An': 8, 'Binh': 9};
  for (final entry in scores.entries) {
    print('${entry.key} scored ${entry.value}');
  }

  // destructure each record with a pattern (Dart 3)
  for (final (name, score) in [('Chi', 7), ('Dung', 10)]) {
    print('$name: $score');
  }
}
I like mango
I like lychee
I like durian
An scored 8
Binh scored 9
Chi: 7
Dung: 10

Tip: Need both the index and the value? Use for (final (i, x) in list.indexed) — indexed yields (index, value) records.

while and do-while

A while loop checks its condition before each pass, so it may run zero times. A do-while loop checks after, so it always runs at least once.

dart · try it yourself
void main() {
  var balance = 100;
  var months = 0;
  while (balance < 150) {
    balance += 20;
    months++;
  }
  print('Reached $balance after $months months');

  var tries = 0;
  do {
    tries++;
    print('Attempt $tries');
  } while (tries < 3);
}
Reached 160 after 3 months
Attempt 1
Attempt 2
Attempt 3

break and continue

  • break exits the loop immediately.
  • continue skips the rest of the current pass and moves on to the next one.
dart · try it yourself
void main() {
  for (var n = 1; n <= 10; n++) {
    if (n % 2 == 0) continue; // skip even numbers
    if (n > 7) break;         // stop completely
    print(n);
  }

  // labels let you break out of an outer loop
  outer:
  for (var row = 0; row < 3; row++) {
    for (var col = 0; col < 3; col++) {
      if (row * col == 2) {
        print('Found at ($row, $col)');
        break outer;
      }
    }
  }
}
1
3
5
7
Found at (1, 2)

forEach and functional style

Collections have a forEach method that takes a function. Many Dart developers prefer for-in for side effects and use methods like map, where and fold to transform data (covered in the Collections lesson).

dart · try it yourself
void main() {
  var cities = ['Hue', 'Da Nang', 'Can Tho'];
  cities.forEach(print);

  var total = 0;
  for (final n in [3, 4, 5]) {
    total += n;
  }
  print('Total: $total');
}
Hue
Da Nang
Can Tho
Total: 12

Collection for — loops inside list literals

Dart lets you put a for (and an if) inside a list, set or map literal. Flutter code uses this all the time to generate children widgets.

dart · try it yourself
void main() {
  var squares = [for (var i = 1; i <= 5; i++) i * i];
  print(squares);

  var names = ['ana', 'ben', 'cam'];
  var labels = [
    'Header',
    for (final n in names) 'User: $n',
    if (names.length > 2) 'Footer',
  ];
  print(labels);
}
[1, 4, 9, 16, 25]
[Header, User: ana, User: ben, User: cam, Footer]

In a Flutter Column you'd write children: [for (final item in items) Text(item)] — exactly the same syntax.

Which loop should I use?

Situation Loop
Visit every element of a collection for-in
Need a counter or a custom step classic for
Repeat until a condition changes while
Run at least once, then check do-while
Build a new list from another collection for or map

Test yourself

How many times does do { ... } while (false); run its body?

  1. 0
  2. 1
  3. Infinitely
  4. It does not compile

What does [for (var i = 0; i < 3; i++) i * 2] produce?

  1. [0, 1, 2]
  2. [2, 4, 6]
  3. [0, 2, 4]
  4. [0, 2, 4, 6]

What does continue do inside a loop?

  1. Exits the loop
  2. Skips to the next iteration
  3. Restarts the loop from the beginning
  4. Pauses the program