Iterable, evaluating a target expression for each iteration and inserting the resulting value(s) directly into the enclosing collection during initialization.
Syntax
The syntax mirrors a standardfor-in loop or C-style for loop but lacks braces {} for the body. The enclosing delimiters determine the type of collection being created.
List Syntax:
Uses square brackets [].
{} with a single expression.
{} with a key-value pair.
Mechanics and Behavior
- Iteration: The operator executes the loop logic synchronously.
- Yielding: For every iteration, the expression following the loop clause is evaluated. The result is appended to the collection being constructed.
- Scope: Variables defined within the
forclause are local to the element generation scope. - Type Inference: The static type of the resulting collection is inferred based on the type of the expression yielded by the loop.
Implementation Examples
List Initialization
In a list literal, thefor element appends results sequentially.
Set Initialization
In a set literal, thefor element appends results while adhering to set uniqueness rules.
Map Construction
In a map literal, thefor element must yield a key-value pair (entry).
Nested Control Flow
Collectionfor can be nested within other control flow elements, such as collection if or other collection for elements, to handle multi-dimensional logic.
Spread Operator Integration
Thefor element can be combined with the spread operator (...) if the expression yields an iterable rather than a single element. This flattens the results into the parent collection.
Master Dart with Deep Grasping Methodology!Learn More





