Skip to main content
The collection for is a control flow element used within collection literals (lists, sets, and maps) to dynamically generate elements. It iterates over an 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 standard for-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 [].
[for (var iterator in iterable) expression]
Set Syntax: Uses curly braces {} with a single expression.
{for (var iterator in iterable) expression}
Map Syntax: Uses curly braces {} with a key-value pair.
{for (var iterator in iterable) keyExpression: valueExpression}

Mechanics and Behavior

  1. Iteration: The operator executes the loop logic synchronously.
  2. Yielding: For every iteration, the expression following the loop clause is evaluated. The result is appended to the collection being constructed.
  3. Scope: Variables defined within the for clause are local to the element generation scope.
  4. 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, the for element appends results sequentially.
final source = [1, 2, 3];

// Generates [10, 20, 30]
final scaled = [
  for (final i in source) i * 10
];

Set Initialization

In a set literal, the for element appends results while adhering to set uniqueness rules.
final numbers = [1, 2, 2, 3];

// Generates {1, 2, 3}
final uniqueSet = {
  for (final i in numbers) i
};

Map Construction

In a map literal, the for element must yield a key-value pair (entry).
final keys = ['a', 'b', 'c'];

// Generates {'a': 0, 'b': 1, 'c': 2}
final indexedMap = {
  for (var i = 0; i < keys.length; i++) 
    keys[i]: i
};

Nested Control Flow

Collection for can be nested within other control flow elements, such as collection if or other collection for elements, to handle multi-dimensional logic.
final matrix = [
  for (var x = 0; x < 2; x++)
    for (var y = 0; y < 2; y++)
      '($x,$y)'
];
// Result: ['(0,0)', '(0,1)', '(1,0)', '(1,1)']

Spread Operator Integration

The for 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.
final groups = [
  [1, 2],
  [3, 4]
];

// Flattens nested lists into [1, 2, 3, 4]
final flat = [
  for (final group in groups) ...group
];
Master Dart with Deep Grasping Methodology!Learn More