CodeBlanks Logo Icon CodeBlanks

Future scheduler

Learn the relation between Future and the scheduler.

The Future scheduler

Futures are scheduler objects. Future.value(x) completes with x as a microtask; Future.sync(fn) calls fn immediately and yields its result; Future.delayed(d, fn) schedules fn as an event after duration d.

When a Future completes, it adds a task to the event queue that resumes awaiting code. Even without await the Future is scheduled — there's just no one waiting for its result.

Example: var f = Future.value(42); schedules the Future immediately; await f then yields the result.

Future.value scheduling

Future.value(x) completes by scheduling a microtask. So right after creating the Future you cannot read its result in the same turn; at least one microtask turn must pass.

Example: var f = Future.value(42); print('a'); var v = await f; print(v);. Order: 'a' prints (sync), then await waits for the microtask, the microtask yields 42, v=42, 42 prints.

This ordering is deterministic: 'a' first, 42 second.

Practice Observe Future.value scheduling

Make main async. Add var f = Future.value(42);. Add print('a');. Add var v = await f; and print(v);.

Starter code

main.dart
void main() {
  // make async; create a Future resolving to 42; print 'a'; await and print the value
}

Sample solution

main.dart
void main() async {
  var f = Future.value(42);
  print('a');
  var v = await f;
  print(v);
}

Expected output

a
42

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match the Future constructors

Term Meaning
Future.value Completes via microtask
Future.sync Calls immediately
Future.delayed Event after duration
Future.error Completes with error

2 When does Future.value resolve?

  • After one microtask turn Correct answer
  • Only inside an Isolate
  • Only with await
  • Immediately, on the same line

Explanation: Future.value resolves after one microtask turn.

3 Future.value call

Question
var f = Future.____(42);
Answer
var f = Future.value(42);

Explanation: Future.value(42) creates a Future that completes with 42.

All lessons in Advanced