for-in loop is a control flow statement that iterates sequentially over the elements of an object implementing the Iterable interface, such as List, Set, or Map.keys. It abstracts the management of the iterator index and termination condition, executing a statement block for each element in the collection.
Syntax
Parameters
candidate: A variable declaration (usingvar,final, or an explicit type) that holds the value of the current element during a specific iteration. This variable is scoped to the loop body.iterable: An expression evaluating to an object that implementsIterable<T>.
Execution Mechanics
When afor-in loop executes, the Dart runtime performs the following operations:
- Iterator Instantiation: The runtime calls the
iteratorgetter on the providediterableobject. - Iteration Cycle:
- The runtime calls
moveNext()on the iterator. - If
moveNext()returnsfalse, the loop terminates. - If
moveNext()returnstrue, thecurrentvalue of the iterator is assigned to thecandidatevariable.
- The runtime calls
- Block Execution: The code block within the braces executes.
- Repeat: Control returns to the start of the Iteration Cycle.
Standard Iteration
In this example, the loop iterates through aList<String>. The variable element is implicitly assigned the value of the current item in the list for each pass.
Pattern Matching and Destructuring
Dart 3 introduced pattern matching, allowing thefor-in loop to destructure elements directly within the loop declaration. This is particularly effective when iterating over lists of records or objects.
Asynchronous Iteration (await for)
For asynchronous sequences of data (Streams), Dart utilizes the await for variation. This construct pauses execution of the enclosing async function until the stream emits a new value or closes.
Master Dart with Deep Grasping Methodology!Learn More





