> ## Documentation Index
> Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Dart Collection For

Dart's collection `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 collection `for` supports standard C-style `for` loops, `for-in` loops, and asynchronous `await for` loops.

**List and Set Literals:**

```dart theme={"dark"}
// Standard for loop
[for (<initialization>; <condition>; <update>) <element_expression>]

// For-in loop
{for (<variable> in <iterable>) <element_expression>}
```

**Map Literals:**

```dart theme={"dark"}
// Maps require key-value pair expressions
{for (<variable> in <iterable>) <key_expression> : <value_expression>}
```

## 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 `for` loop 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, `for` acts as an element generator rather than a control flow statement. It does not support block bodies (`{}`) or statements like `return` or `break`.

## Code Examples

**Standard `for` Loop in a List:**

```dart theme={"dark"}
final integers = [1, 2, for (var i = 3; i <= 5; i++) i];
// Result: [1, 2, 3, 4, 5]
```

**`for-in` Loop in a Set:**

```dart theme={"dark"}
final source = [1, 2, 3];
final squaredSet = <int>{for (final num in source) num * num};
// Result: {1, 4, 9}
```

**`for` Loop in a Map:**

```dart theme={"dark"}
final keys = ['a', 'b', 'c'];
final charMap = {for (var i = 0; i < keys.length; i++) keys[i]: i};
// Result: {'a': 0, 'b': 1, 'c': 2}
```

## Advanced Composition

Because the collection `for` 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`:**

```dart theme={"dark"}
final matrix = [
  for (var i = 0; i < 3; i++)
    for (var j = 0; j < 3; j++)
      if (i == j) 1 else 0
];
// Result: [1, 0, 0, 0, 1, 0, 0, 0, 1]
```

**Asynchronous Iteration (`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.

```dart theme={"dark"}
Future<List<int>> consumeStream(Stream<int> stream) async {
  return [
    0, 
    await for (final value in stream) value,
    99
  ];
}
```

<div
  style={{ 
display: "flex", 
justifyContent: "space-between", 
alignItems: "center", 
maxWidth: "754px", 
padding: "1rem 0",
marginBottom: "24px"
}}
>
  <span style={{ fontWeight: "bold", fontSize: "1.25rem", color: "var(--tw-prose-headings)", fontFamily: "Inter, ui-sans-serif, system-ui, sans-serif" }}>Tired of Poor Dart Skills? Fix That With Deep Grasping!</span>

  <a
    href="https://syntblaze.com"
    target="_blank"
    style={{ 
  marginLeft: "24px",
  textDecoration: "none", 
  backgroundColor: "#007AFF",
  color: "#ffffff", 
  padding: "6px 16px", 
  borderRadius: "16px",
  fontSize: "0.9rem",
  fontWeight: "600",
  textAlign: "center",
  transition: "background-color 0.2s ease"
}}
  >
    Learn More
  </a>
</div>

<div style={{ display: "flex", gap: "12px", flexWrap: "wrap" }}>
  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/skill-tracking.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=b9b0305c93bb501c9e767b5c76c88835" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/skill-tracking.png" />

  <img src="https://mintcdn.com/syntblazellc/23tyuOzaWS88qFlc/images/nuggets.png?fit=max&auto=format&n=23tyuOzaWS88qFlc&q=85&s=c86c80197299762989e9b882419b2109" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/nuggets.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/bite-sized-exercises.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=a65f9a38c37ff28ab73ed783c53c60e3" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/bite-sized-exercises.png" />
</div>

<div style={{ display: "flex", gap: "12px", flexWrap: "wrap", marginTop: "12px" }}>
  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/mastery-chain.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=748a1763454713e679260fbb95f154a2" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/mastery-chain.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/element-previews.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=242f61448ff5dd6deaaab2dccc13b507" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/element-previews.png" />

  <img src="https://mintcdn.com/syntblazellc/-L0ums_2lctDSZ1l/images/element-explanations.png?fit=max&auto=format&n=-L0ums_2lctDSZ1l&q=85&s=cf0fc1c31f9cd0fc26716781be05fbc9" style={{ width: "30%", minWidth: 60 }} width="621" height="1344" data-path="images/element-explanations.png" />
</div>
