for-in loop in Dart is a control flow statement designed for sequential iteration over objects that implement the Iterable interface. It abstracts the underlying Iterator mechanics, providing a concise syntax to access each element in a collection sequentially without manual index management.
Syntax
declaration|identifier: Either a new variable declaration (scoped to the loop body) or an existing identifier (externally scoped) that receives the current element in the iteration.iterable: An expression that evaluates to a DartIterable.
Underlying Mechanics
When afor-in loop executes, Dart performs the following operations under the hood:
- Evaluates the
iterableexpression. - Calls the
.iteratorgetter on the resultingIterableto obtain anIteratorobject. - Enters a loop that calls
moveNext()on theIterator. - If
moveNext()returnstrue, it assigns the value ofIterator.currentto the loop variable and executes the loop body. - If
moveNext()returnsfalse, the loop terminates.
Variable Binding and Scoping
The loop variable can be newly declared within the loop construct or it can reference an existing, externally scoped variable.Pattern Matching Integration
As of Dart 3.0, thefor-in loop supports destructuring patterns directly within the declaration clause. This allows for unpacking complex data structures, such as Records or nested collections, during iteration.
Technical Constraints
- No Index Access: The
for-inloop does not expose an iteration counter or index. If an index is required, developers must use a standardforloop or the.indexedgetter (e.g.,for (final (index, item) in items.indexed)). - Concurrent Modification: The
for-inlanguage construct itself does not enforce structural immutability; it merely invokesmoveNext(). However, the specificIteratorimplementations of standard library collections (such asListandSet) are designed to be fail-fast. Attempting to modify the length or structure of these standard collections during iteration will cause their iterators to throw aConcurrentModificationError. CustomIterableimplementations dictate their own modification rules and may allow mutations without throwing an error. - Synchronous Only: The standard
for-inloop operates strictly on synchronousIterableobjects. To iterate over asynchronous data sequences (Stream), Dart provides theawait forvariant.
Tired of Poor Dart Skills? Fix That With Deep Grasping!Learn More





