---
title: "Walking Through Collections with for-in Loops in Dart"
date: "2026-12-03T10:01:00+07:00"
description: "Master Dart's for-in loop: iterate Lists, Sets and Maps, destructure with patterns, dodge mutation hazards, and choose between for-in, forEach, and where."
author: "AI Assistant"
image: "https://blog.redlinesoft.net/images/post/dart-for-in-collection-loops.jpg"
alt: "Conceptual illustration of a loop arrow walking sequentially across a chain of connected collection nodes"
tags: ['dart', 'dart-language', 'iterables', 'loops', 'collections']
---

Most Dart programs spend their time walking through collections, and the `for-in` loop is the cleanest way to do it. One line tells the reader "visit every element," without index bookkeeping or callback nesting.

## Why for-in wins for collections

Whenever you don't need the index, `for-in` is the idiomatic choice. The Dart language tour recommends it explicitly for `Iterable` types like `List` and `Set`, and the iterable tutorial calls it the easiest way to read the elements of an iterable sequentially. Behind the scenes it drives an `Iterator`, but you almost never touch that API directly — `for-in` is easier to read, easier to get right, and far less prone to off-by-one errors than manual indexing.

```dart
const candidates = ['Alice', 'Bob', 'Claire'];

for (final candidate in candidates) {
  print('$candidate is interviewing today.');
}
```

The loop variable is declared inside the loop header and is assigned one element from the collection per iteration. Because you almost never reassign it, prefer `final` over `var` — it signals that each element binding is fixed.

## Iterating a Map yields MapEntry objects

A `Map` is not an `Iterable`, so `for-in` over the map itself would give you nothing useful... except that Dart's `Map` *does* implement `Iterable<MapEntry<K, V>>`. Each element you receive is a `MapEntry` with `key` and `value`:

```dart
const scores = {'math': 92, 'english': 85, 'science': 78};

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

You can also iterate `scores.keys` or `scores.values` directly when you only need one half. Note that Effective Dart's ban on `forEach` with a function literal does *not* apply to `Map.forEach()`, because maps aren't iterable — but `for-in` over `.entries` reads just as well.

## Destructuring patterns in for-in

Dart 3 patterns make `for-in` even more powerful: the loop head accepts a full pattern, so you can destructure each element as it arrives:

```dart
class Candidate {
  final String name;
  final int yearsExperience;
  const Candidate(this.name, this.yearsExperience);
}

const candidates = [Candidate('Alice', 7), Candidate('Bob', 3)];

for (final Candidate(:name, :yearsExperience) in candidates) {
  print('$name has $yearsExperience years of experience.');
}
```

Object patterns extract named fields in place, and list or record patterns work the same way — `for (final [x, y] in pairs)` pulls apart two-element lists without touching `.first` or `.last`.

## The loop variable is a fresh local every iteration

The element variable is a *local* variable scoped to the loop body. Reassigning it changes only that local binding, never the underlying collection:

```dart
final names = ['Alice', 'Bob'];

for (var name in names) {
  name = name.toUpperCase(); // Reassigns the local only.
  print(name);
}

print(names); // Still ['Alice', 'Bob'] — the source is untouched.
```

This also means closures created inside the loop capture the current iteration's value, so a list of callbacks prints `0` then `1`, not `2` then `2` as it would in JavaScript.

## Don't mutate the collection while iterating

Because `for-in` drives an iterator, adding or removing elements mid-loop is a hazard. Mutating a `List` during iteration throws `ConcurrentModificationError` at runtime:

```dart
final numbers = [1, 2, 3];

for (final n in numbers) {
  numbers.remove(n); // Throws ConcurrentModificationError.
}
```

Two safe patterns exist. Either iterate over a snapshot — `for (final n in List.of(numbers))` gives the loop its own copy to walk — or let the loop finish over untouched data and perform the mutation afterwards with `numbers.removeWhere((n) => n.isEven)`. The same advice applies to removing elements inside a `for-in` over a `Set`: collect first, delete later.

## Choosing between for-in, index for, forEach, and where

| Approach | Best for | Drawback |
|---|---|---|
| `for (final x in list)` | Reading every element | No index or early exit across nesting |
| `for (var i = 0; i < n; i++)` | When you need the index | Verbose, easy to get bounds wrong |
| `list.forEach((x) { ... })` | Invoking an existing function | Function literals are discouraged by Effective Dart |
| `list.where((x) => ...)` | Filtering into a new iterable | Lazy — does nothing until consumed |

Effective Dart's linter rule `avoid_function_literals_in_foreach_calls` says it plainly: *AVOID* `Iterable.forEach` with a function literal. If you want to iterate, use a loop; if you want to invoke an already-named function, `forEach` is fine:

```dart
// Preferred
for (final person in people) {
  print(person);
}

// Acceptable — a tear-off, not a literal
people.forEach(print);
```

For filtering, chain `where` and then loop over the result; `where` returns another `Iterable`, which you can feed straight into `for-in`. See `dart-arrow-functions-expression-bodies.md` for writing those filter callbacks with `=>`.

## Lazy Iterables: for-in forces evaluation

Methods like `map()` and `where()` return *lazy* `Iterable`s — no work happens until something iterates them. A `for-in` loop is that trigger:

```dart
final numbers = [1, 2, 3];
final doubled = numbers.map((n) => n * 2); // Nothing computed yet.
print(doubled); // Prints a lazy map iterable description.

for (final n in doubled) {
  print(n); // Now 2, 4, 6 are computed, one per step.
}
```

Laziness cuts both ways: it avoids intermediate lists, but an infinite `Iterable` built with `sync*` will loop forever inside `for-in`. Only iterate when you truly want every element. And if you need to peek at items by position — `iterable[1]` doesn't exist on a bare `Iterable` — either use `elementAt(1)`, which may walk the sequence in linear time, or call `.toList()` once up front and index into that.

## Nested loops and the wildcard variable

`for-in` nests naturally — an inner loop over a row's cells inside an outer loop over rows — and each level gets its own fresh element variable, so shadowing is never a problem. When you must iterate purely for side effects and don't care about the element at all, Dart 3.7 introduced the wildcard variable: writing `for (var _ in List.filled(3, 0))` prints `tick` three times while declaring no real binding, making "I'm iterating for the effect only" obvious at a glance. For control over which iteration you're in — skipping or exiting a nested loop — see `dart-break-continue-labels.md`.

## Takeaways

`for-in` is the default way to walk any `Iterable`: it reads cleanly, binds a fresh local per element, and pairs perfectly with pattern destructuring. Keep the source collection stable while iterating, reach for `forEach` only with tear-offs, and remember that lazy `Iterables` come alive the moment your loop starts.

**Takeaway:** Prefer `for (final element in collection)` for reading collections, destructure with patterns when it clarifies, and never mutate a collection while its iterator is running.

## References

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