---
title: "Repeating Work with for, while, and do-while Loops in Dart"
date: "2026-12-03T10:00:00+07:00"
description: "C-style for, closures that capture values not variables, for-in over iterables, while versus do-while, side-effect conditions, break, labels, and forEach etiquette."
author: "AI Assistant"
image: "https://blog.redlinesoft.net/images/post/dart-for-while-do-while-loops.jpg"
alt: "A circular arrow diagram of Dart for, for-in, while, and do-while loop forms with break and continue"
tags: ['dart', 'dart-language', 'control-flow', 'iterables', 'loops']
---

Every repetitive task eventually becomes a loop, and Dart gives you four loop forms plus a handful of escape hatches. Picking the right one is mostly about how much you know before the first iteration starts.

## The C-style for loop

The classic three-part header — initialization, condition, increment — is still the right tool when you need a counter, such as building up a `StringBuffer('Dart is fun')` with five exclamation marks. More importantly, closures inside Dart's `for` loops capture the *value* of the index on each iteration, so the callbacks below print `0` and `1` exactly as you would hope. The equivalent code in JavaScript captures the shared variable and prints `2` and `2`; Dart sidesteps that classic bug by treating each iteration's `i` as its own value:

```dart
void main() {
  final callbacks = <void Function()>[];
  for (var i = 0; i < 2; i++) {
    callbacks.add(() => print(i));
  }
  for (final callback in callbacks) {
    callback(); // prints 0, then 1 — Dart captures the value
  }
}
```

## for-in over an iterable

When you are walking a `List`, `Set`, or any other `Iterable` and do not need the index, `for-in` is the idiomatic choice. The loop variable is a fresh local for each iteration: reassigning `candidate` inside the body never touches the underlying list. Patterns work here too — `for (final MapEntry(:key, value: count) in history.entries)` destructures each entry inline, as shown in `dart-patterns-and-records.md`:

```dart
class Candidate {
  final String name;
  final int yearsExperience;
  Candidate(this.name, this.yearsExperience);
}
void main() {
  final candidates = [Candidate('Ada', 7), Candidate('Linus', 4)];
  for (final candidate in candidates) {
    if (candidate.yearsExperience < 5) continue;
    print('${candidate.name} is ready for interview');
  }
}
```

## while versus do-while

The only structural difference between the two condition-based loops is *when* the condition is evaluated, and that decides the semantics: a `while` loop may run zero times, while a `do-while` body always runs at least once. A `while` loop is the safe default; reach for `do-while` only when the body must happen before you can even evaluate the condition — displaying a menu before asking whether to show it again, for example:

| Loop | Condition checked | Body runs at least once? | Typical use |
|---|---|---|---|
| `while` | Before each iteration | No — zero runs possible | Continuation decided up front |
| `do-while` | After each iteration | Yes — always one run | Menus, prompts, first-pass work |

```dart
void main() {
  var tries = 0;
  while (tries < 3) {
    tries++;
  }
  do {
    tries++;
  } while (tries < 5);
  print(tries); // 5 — while ran 3 times, do-while 2 more
}
```

## Conditions with side effects

Both loops allow the condition to do real work, and a common idiom reads from a source until it runs dry. This works, and flow analysis even promotes `line` to non-null inside the body. The hazard is readability: side effects buried in conditions are easy to miss in review, and they make the loop's termination argument harder to check. When the side effect *is* the point of the first iteration, `do-while` states that intent directly; when the condition is complex, moving the update into the body usually makes the loop safer to modify:

```dart
final lines = ['alpha', 'beta'];
var index = 0;
String? nextLine() => index < lines.length ? lines[index++] : null;
void main() {
  String? line;
  while ((line = nextLine()) != null) {
    print('got $line');
  }
}
```

## break, continue, and infinite loops

`break` leaves the innermost loop immediately, `continue` skips to its next iteration — the `for-in` example above uses `continue` to skip an unqualified candidate — and `while (true)` plus a well-placed `break` is the standard way to express "loop until something happens":

```dart
void main() {
  var processed = 0;
  while (true) {
    processed++;
    if (processed >= 3) break;
  }
  print('processed $processed'); // processed 3
}
```

An unbounded loop is only safe when some exit is guaranteed: a `break`, a `return`, or a condition that provably becomes false. Reviewers should be able to name that exit without tracing the whole body.

## Labels for nested loops

In nested loops, `break` and `continue` target the innermost loop. A label lets you target an outer one: the program below prints four pairs and then leaves both loops at once. The same labeling syntax works with `continue outerLoop;` and with switch cases — `dart-break-continue-labels.md` walks through those variants, including labels on `while` and `do-while`:

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

## Iterable alternatives: where and forEach

If you already have an `Iterable`, `where()` and `forEach()` look like loop replacements, and Effective Dart draws a sharp line between them: *AVOID using `Iterable.forEach()` with a function literal*, backed by the `avoid_function_literals_in_foreach_calls` linter. In Dart, iterating with a loop is the idiomatic default, and `forEach(print)` is perfectly acceptable because it passes an existing function rather than a fresh closure. The exception is `Map.forEach()`, which is not part of `Iterable` and carries no such rule:

```dart
void main() {
  final people = ['Ada', 'Grace', 'Linus'];
  for (final person in people) {
    print(person); // preferred: a plain for-in loop
  }
  people.forEach(print); // fine — an existing function, not a literal
  print(people.where((p) => p.length > 3).toList()); // [Grace, Linus]
}
```

## Choosing the right loop

| Loop | Use when | Watch out for |
|---|---|---|
| C-style `for` | You need an index or a counter | Off-by-one bounds; prefer `for-in` when the index is unused |
| `for-in` | Iterating any `Iterable` | Cannot skip backward; loop variable is per-iteration |
| `while` | Continuation depends on a checked condition | May run zero times; keep the condition honest |
| `do-while` | The body must run before the condition is known | Always runs once — even when it should not |

On performance: do not choose a loop form based on speed. The VM and AOT compilers reduce these constructs to the same underlying iteration code in hot paths, so readability and a provable termination condition decide the question — profile before optimizing, and reach for `where()`/`map()` chains only when they genuinely read better than the loop they replace. Control flow like an early `break` almost always belongs in a real loop, alongside the branching tools from `dart-if-else-switch-statements.md`.

## Takeaways

- Use `for` when you need an index, `for-in` for anything `Iterable`, `while` when the condition comes first, and `do-while` when the body must run once before you can decide.
- Closures capture each iteration's value in Dart, so the JavaScript `for`-loop trap does not apply here.
- Side-effecting conditions are concise but hide the termination argument; make loop exits obvious to reviewers.
- `while (true)` plus a guaranteed `break` is a legitimate pattern; labels extend `break` and `continue` to outer loops.
- Prefer `for-in` over `forEach` with a function literal, and let readability — not imagined overhead — choose the loop.

**Takeaway:** Pick the loop form that states your iteration contract — unknown count checked up front, guaranteed first run, or plain iterable traversal — and keep its exit condition visible at a glance.

## References

- https://dart.dev/language/loops
- https://dart.dev/effective-dart/usage
- https://dart.dev/language/patterns
