Phase 2 · Modern & Asynchronous DartModule 13~46 min read

Streams & Reactive Data

Model sequences of asynchronous values with safe subscription ownership, transformations, errors, and real-time repositories.

What you'll learn

Model sequences of asynchronous values with safe subscription ownership, transformations, errors, and real-time repositories. The lesson turns the APIs into a repeatable engineering workflow instead of a collection of isolated snippets.

By the end of this lesson, you'll be able to:

  • Apply Stream kinds in a production-shaped Flutter feature
  • Apply Subscriptions in a production-shaped Flutter feature
  • Apply async* and yield in a production-shaped Flutter feature
  • Apply Transformations in a production-shaped Flutter feature

Core mental model

Connect each API to the decision it supports. Flutter code stays maintainable when state, ownership, lifecycle, and platform boundaries are explicit.

ConceptWhat it meansDecision rule
SubscriptionAn owned connection to a stream's eventsCancel it when the owning lifecycle ends
Broadcast streamMultiple listeners may observe the same event sourceUse only when independent subscribers are a real requirement
async*An asynchronous generator that yields a streamUse for readable sequences with structured cleanup

Professional workflow

Work in small vertical slices and keep behavior observable from the first iteration.

  1. Define the lifecycle-safe progress stream boundary: user goal, inputs, visible states, ownership, and expected failures.
  2. Build the smallest working vertical slice with typed data and explicit dependencies.
  3. Represent loading, empty, success, and failure behavior where the feature can encounter them.
  4. Verify logic away from the UI, then exercise the rendered behavior at its public boundary.
  5. Inspect lifecycle, accessibility, performance, security, and platform behavior before widening the feature.
  6. Refactor only after behavior is protected by repeatable evidence.

Protect the frame

Keep build methods predictable, move side effects to explicit owners, and measure before introducing caches, isolates, or architectural layers.

Guided Flutter lab

Build a focused lifecycle-safe progress stream slice

This compact example keeps the important ownership and data-flow decisions visible so the behavior is easy to extend and test.

lib/progress_stream.dart
Stream<int> distinctProgress(Stream<int> source) async* {
  var previous = -1;
  await for (final value in source) {
    final safe = value.clamp(0, 100);
    if (safe == previous) continue;
    previous = safe;
    yield safe;
  }
}

final subscription = distinctProgress(repository.watchProgress('dart'))
    .listen((percent) => print('Progress: $percent%'));

// The lifecycle owner must eventually call:
// await subscription.cancel();

Production practice

Contract

Define the lifecycle-safe progress stream inputs, outputs, owner, lifecycle, visible states, and platform assumptions before selecting APIs or packages.

Verification

Protect pure rules with unit tests and the rendered public contract with widget or integration evidence; include one unavailable or failure case.

Operations

Keep dependencies replaceable, log actionable context without user secrets, and measure user-visible behavior before optimizing.

Common failure mode

Creating a StreamController where an existing stream transformation is enough adds manual lifecycle, error, and close responsibilities.

Independent workshop

Extend the guided lab into a review-ready lifecycle-safe progress stream feature that fits the running course portfolio app.

Your finished workshop must include:

  • Stream kinds
  • Subscriptions
  • async* and yield
  • Transformations
  • Controllers
  • Automated verification and a short design note

Definition of done

Demonstrate the happy path, an empty or unavailable state, and at least one failure path. Add an automated check and a short note explaining one design decision.

Recap & quick check

Key takeaways

  • Subscription: Cancel it when the owning lifecycle ends
  • Broadcast stream: Use only when independent subscribers are a real requirement
  • async*: Use for readable sequences with structured cleanup

Quick check

1. Which rule best applies to Subscription?

2. Which rule best applies to Broadcast stream?

3. Which rule best applies to async*?

Next: Isolates & CPU-Bound Concurrency