Skip to content
Tutorials Center
My learning

Topics

Lesson 8 of 73 ยท Dart essentials

Futures, async/await and Streams

Learn Dart asynchronous programming for Flutter: the event loop, Future, async/await, Stream, StreamController and isolates, with runnable JavaScript stand-ins.

Almost everything interesting in an app takes time: reading a file, calling a server, waiting for a timer, listening to the user's location. If your code stopped and waited for each of those, the screen would freeze, because Flutter draws every frame on the same thread that runs your Dart code. Dart solves this with asynchronous programming: you start an operation, keep the app responsive, and get the result later.

Dart has two main tools for this. A Future represents one value that will arrive later. A Stream represents many values that arrive over time. This lesson explains how both work, how async and await make them easy to read, and when you need a separate isolate. It builds on Dart basics, null safety and collections and generics, because Future<T> and Stream<T> are generic types.

What is real here? The Dart code in plain code blocks is real Dart, but this site cannot run Dart. The live examples are JavaScript stand-ins: JavaScript has an almost identical model (promises, async/await, async iterators), so they show the same behavior with the same ordering.

One thread, many waits

One isolate Your Dart code runs on one thread.
Waiting is free While you wait, other events run.
Event loop It picks the next task from a queue.
1 / 2

The event loop

A Dart program runs inside an isolate. Each isolate has its own memory, one thread, and an event loop. The loop has two queues: the microtask queue (small jobs that must run right away, such as continuing a completed Future) and the event queue (timers, taps, network responses, file reads). The loop always empties the microtask queue first, then takes one event, then checks microtasks again.

flowchart TD
  A["Run main()"] --> B["Run all microtasks"]
  B --> C{"Event queue empty?"}
  C -- "no" --> D["Take one event and run it"]
  D --> B
  C -- "yes" --> E["Wait for new events"]
  E --> C

The event loop: microtasks first, then one event at a time.

The key consequence: a long synchronous loop blocks everything, including drawing. Asynchronous code does not make work faster. It lets the loop do other things while an external operation (the network, the disk) is busy.

Futures

A Future<T> is an object that will complete with a value of type T or with an error. It has three states: uncompleted, completed with a value, completed with an error.

DART
Future<String> fetchGreeting() {
  return Future.delayed(
    const Duration(seconds: 1),
    () => 'Hello from the future',
  );
}

void main() {
  fetchGreeting()
      .then((text) => print(text))
      .catchError((Object e) => print('Failed: $e'))
      .whenComplete(() => print('Done'));
  print('This prints first');
}

then registers a callback for the value, catchError for the error, and whenComplete runs either way (like finally). Notice that main does not wait: "This prints first" appears before the greeting.

async and await

Chains of then get hard to read. Marking a function async lets you write await inside it. await pauses that function (not the whole app) until the future completes, then gives you the value. An async function always returns a Future.

DART
Future<void> showProfile() async {
  try {
    final user = await loadUser(7);
    final posts = await loadPosts(user.id);
    print('${user.name} has ${posts.length} posts');
  } catch (e) {
    print('Could not load profile: $e');
  } finally {
    print('Finished');
  }
}

This reads top to bottom like ordinary code, and try/catch works for errors. When the two awaits do not depend on each other, start both first and wait together:

DART
final results = await Future.wait([loadUser(7), loadSettings()]);
JS Awaiting one by one vs together

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Promise.all plays the role of Dart's Future.wait. Sequential awaits add their durations; waiting together takes as long as the slowest one.

Ordering: what runs when?

Code before the first await runs synchronously. After it, the rest of the function becomes a microtask-style continuation. This stand-in shows the order you would see in Dart too:

JS Sync code, microtasks, then events

Press Run (or Ctrl + Enter) to see the console output here.

No output.

In Dart, Future.microtask and the continuation after await on a completed future behave like the promise callbacks here, and Future(() => ...) or Timer.run schedule on the event queue like setTimeout. The exact interleaving of several microtasks is an implementation detail, so never depend on tiny ordering differences.

Streams

A Stream<T> delivers a sequence of values (and possibly an error, then a "done" signal). Think of taps, keystrokes, a WebSocket, sensor readings or a countdown. You can consume a stream with await for inside an async function, or with listen.

DART
Stream<int> countdown(int from) async* {
  for (var i = from; i > 0; i--) {
    await Future.delayed(const Duration(milliseconds: 500));
    yield i;
  }
}

Future<void> main() async {
  await for (final n in countdown(3)) {
    print(n);
  }
  print('Liftoff');
}

A function marked async* is a generator: each yield pushes a value into the stream. Streams are usually single-subscription (one listener, values are buffered until someone listens). A broadcast stream (stream.asBroadcastStream() or StreamController.broadcast()) allows many listeners but does not remember values for late listeners.

StreamController

When values come from callbacks instead of a loop, create a StreamController:

DART
final controller = StreamController<String>();

final subscription = controller.stream.listen(
  (message) => print('Got $message'),
  onError: (Object e) => print('Error: $e'),
  onDone: () => print('Closed'),
);

controller.add('hello');
controller.add('world');
controller.addError(StateError('oops'));
await controller.close();
await subscription.cancel();

Always close() controllers and cancel() subscriptions when you are done. In Flutter you do this in a widget's dispose method (StatefulWidget and setState), otherwise you leak memory and keep processing events for a screen that is gone.

JS A stream with a controller and an async iterator

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The consumer loop has the same shape as Dart's await for: it suspends between values and ends when the stream is closed.

Useful stream operations

Streams have many methods that return new streams, much like list methods do: map, where, take, skip, distinct, asyncMap, transform. Common terminal helpers are first, last, toList(), length and fold.

DART
final evens = Stream.periodic(const Duration(milliseconds: 200), (i) => i)
    .where((n) => n.isEven)
    .take(3);

print(await evens.toList()); // [0, 2, 4]

Flutter has widgets that rebuild from futures and streams: FutureBuilder and StreamBuilder. You will meet them in FutureBuilder, StreamBuilder and async UI.

Isolates: real parallel work

async does not use extra threads. If you must do heavy computation (decoding a huge JSON file, resizing an image), the work still blocks the event loop and the UI would drop frames. For that, run it in another isolate: a separate worker with its own memory and event loop. Isolates share nothing and talk by sending messages.

DART
final total = await Isolate.run(() {
  var sum = 0;
  for (var i = 0; i < 500000000; i++) {
    sum += i;
  }
  return sum;
});

Isolate.run starts a worker, runs the closure, returns the result as a Future, and shuts the worker down. Flutter also offers compute(), a thin wrapper for the same idea. Use isolates for CPU-bound work, not for waiting on the network (that is already non-blocking). Isolates are not available in Dart compiled to JavaScript for the web in the same way, so check the platform notes on Flutter on web and desktop.

Common mistakes

  • Forgetting await. Without it you get a Future object instead of its value, and errors escape unnoticed. The analyzer lint unawaited_futures helps.
  • Doing heavy loops in async functions and expecting the UI to stay smooth. Move CPU work to an isolate.
  • Listening twice to a single-subscription stream. Use a broadcast stream when several listeners are needed.
  • Never closing controllers or canceling subscriptions.
  • Using BuildContext after an await. The widget may be gone. See BuildContext and InheritedWidget.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does an async function in Dart always return?

    Marking a function async wraps its result in a Future, even if the body never awaits anything.
  2. 2. Which statement about the event loop is correct?

    The loop empties the microtask queue, then takes one event. await only pauses the current function; the isolate keeps handling other events.
  3. 3. You need to read many values over time from a WebSocket. Which type fits best?

    A Future holds a single result. A Stream delivers zero or more values over time.
  4. 4. When should you use Isolate.run?

    Network waits are already non-blocking. Isolates are for CPU-heavy work, and they share no memory; they communicate by messages.

Summary

  • Dart runs your code on one thread per isolate, driven by an event loop with a microtask queue and an event queue.
  • A Future<T> is one value (or error) arriving later; async/await makes it read like normal code and works with try/catch.
  • Start independent futures together and use Future.wait to save time.
  • A Stream<T> is a sequence over time: use async*/yield, await for, listen and StreamController.
  • Close controllers and cancel subscriptions in dispose.
  • Use isolates for CPU-heavy work; they share no memory and communicate by messages.

Next: Everything Is a Widget