Skip to main content

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.

The await for loop is an asynchronous iteration construct in Dart used to consume events from a Stream. It suspends the execution of the enclosing async function until the stream emits a data event, executes the loop body with that event, and continues this process until the stream is closed.

Syntax

await for (variableDeclaration in streamExpression) {
  // Executes for each data event emitted by the stream
}

Execution Mechanics

To utilize an await for loop, the enclosing function must be marked with the async or async* modifier. The loop operates through the following lifecycle:
  1. Subscription: The loop implicitly subscribes to the provided Stream.
  2. Suspension: The execution of the enclosing function is suspended, yielding control back to the Dart event loop while waiting for the stream to emit an event.
  3. Execution: When a data event is emitted, the variable is bound to the event data, and the loop body executes.
  4. Iteration: Steps 2 and 3 repeat for every subsequent event.
  5. Termination: The loop completes naturally, and execution proceeds to the next statement, only when the stream emits a “done” event indicating it is closed.

Premature Termination and Cancellation

You can interrupt an await for loop using standard control flow statements such as break or return. When the loop is exited prematurely, Dart automatically cancels the underlying stream subscription, preventing memory leaks and stopping further event generation if the stream is lazy.

Error Handling

If the stream emits an error event, the await for loop throws that error synchronously within the asynchronous context. The loop terminates immediately, and the subscription is canceled. These errors can be intercepted by wrapping the await for loop in a standard try-catch block.

Code Example

Stream<int> generateStream() async* {
  yield 1;
  yield 2;
  // Stream closes automatically after the last yield
}

Future<void> processStream() async {
  try {
    await for (final int event in generateStream()) {
      print(event);
      
      if (event == 2) {
        break; // Exits the loop and cancels the stream subscription
      }
    }
  } catch (e) {
    // Catches any error events emitted by the stream
    print('Caught stream error: $e');
  }
}
Master Dart with Deep Grasping Methodology!Learn More