๐ŸŽ“ A1Learner
๐Ÿ”
0 of 37 lessons completed

Dart Futures

A Future is an object that will hold a value that arrives later. A program can attach work to run when that value arrives.

A value that arrives later

Future.value already holds 42, and then prints it when it arrives. The waiting line prints first because it is synchronous.

void main() {
  Future.value(42).then((v) => print(v));
  print('waiting');
}

A chain that changes the value

Each then step receives the value from the step before it. The chain turns 2 into 5 and then into 50.

void main() {
  Future.value(2)
      .then((v) => v + 3)
      .then((v) => v * 10)
      .then((v) => print(v));
}

The order of Future work

Synchronous prints run first, then microtask work, then Future event work. The four lines always appear in this order.

void main() {
  print('start');
  Future.microtask(() => print('microtask step'));
  Future(() => print('future event'));
  print('end');
}

Work after a zero delay

Future.delayed with Duration.zero schedules its work for a later turn. The synchronous line prints first.

void main() {
  Future.delayed(Duration.zero, () => print('delayed step'));
  print('first step');
}

Recovering from an error

The error skips the then step and reaches catchError instead. catchError prints a fallback line, so the program ends normally.

void main() {
  Future<int>.error('load failed')
      .then((v) => print(v))
      .catchError((e) => print('using fallback'));
}

Example

void main() {
  print('loading');
  Future.value(3)
      .then((v) => v * 4)
      .then((v) => print('result $v'));
  print('requested');
}

Key points

  • A Future completes with a value or with an error.
  • Future.value makes a Future that already holds a value.
  • then registers work to run when the value arrives.
  • A then call can return a new value for the next then in a chain.
  • Synchronous prints run before any Future work.
  • Future.delayed schedules work after a delay.
  • catchError registers work to run when a Future completes with an error.

In this example, the first print shows loading and the last synchronous print shows requested. The chain then multiplies 3 by 4 and prints result 12. The chained print runs after both synchronous prints.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท DartPad

Exercise

In the order program, which line prints last?