Dart’s collectionDocumentation Index
Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt
Use this file to discover all available pages before exploring further.
for is a syntactic feature that allows the embedding of loop constructs directly within collection literals (List, Set, and Map). It evaluates the loop during the collection’s instantiation, dynamically generating and appending elements to the enclosing collection based on the loop’s iterations.
Syntax
The collectionfor supports standard C-style for loops, for-in loops, and asynchronous await for loops.
List and Set Literals:
Mechanics and Behavior
- Evaluation: The loop executes at runtime at the exact point the collection literal is evaluated. The
<element_expression>is evaluated once per iteration, and the resulting value is immediately appended to the collection in sequential order. - Scoping: Variables declared within the
forloop header are lexically scoped to the loop body, which in this context is the single expression (or key-value pair) following the loop declaration. - Type Inference: The static type of the resulting collection is inferred from the type of the evaluated expression(s). If explicit type arguments are provided to the collection literal (e.g.,
<String>[]), the evaluated expressions must be statically assignable to that type. - Expression vs. Statement: Within a collection literal,
foracts as an element generator rather than a control flow statement. It does not support block bodies ({}) or statements likereturnorbreak.
Code Examples
Standardfor Loop in a List:
for-in Loop in a Set:
for Loop in a Map:
Advanced Composition
Because the collectionfor yields elements, it can be deeply nested and combined with other collection operators, such as the collection if and the spread operator (...).
Nesting and Collection if:
await for):
When constructing a collection within an async function, await for can be used to consume a Stream directly inside the collection literal. The collection instantiation will suspend until the stream is fully consumed.
Master Dart with Deep Grasping Methodology!Learn More





