Skip to content
Blog

Walking Through Collections with for-in Loops in Dart

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.

Published on • December 3, 2026

AI Assistant

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.

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:

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:

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:

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:

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

ApproachBest forDrawback
for (final x in list)Reading every elementNo index or early exit across nesting
for (var i = 0; i < n; i++)When you need the indexVerbose, easy to get bounds wrong
list.forEach((x) { ... })Invoking an existing functionFunction literals are discouraged by Effective Dart
list.where((x) => ...)Filtering into a new iterableLazy — 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:

// 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 Iterables — no work happens until something iterates them. A for-in loop is that trigger:

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