CodeBlanks Logo Icon CodeBlanks

Completer

Learn manual Future control with Completer.

Completer

Completer is used to complete a Future manually. Usually APIs produce Futures; but sometimes you want to create your own Future and complete it when you choose. Completer does this.

Example: var c = Completer<String>();. This produces a String Future. You give the value with c.complete('Done');. You access the Future with c.future and wait with await.

Completer lives in the dart:async library; import 'dart:async'; is required. In real apps it is used to turn callbacks into Futures.

Completer flow

The flow of using a Completer is: first create with Completer<T>(). Then give the value with complete(value). Finally access the Future with c.future and wait with await.

Example: var c = Completer<String>(); c.complete('Done'); var r = await c.future; print(r);. Output: Done. When complete is called the Future finishes at once.

This structure is used to turn event-based APIs into Futures. For example you complete a Completer when a button is clicked; you wait for the click with await.

Practice Complete a Future with Completer

import 'dart:async' is already added. void main() async is already written. Create a Completer<String>(). Give the value with c.complete('Done'). Wait with await c.future and print the result with print.

Starter code

main.dart
import 'dart:async';

void main() async {
  // create a Completer<String>, give a value with complete, await the future and print
}

Sample solution

main.dart
import 'dart:async';

void main() async {
  var c = Completer<String>();
  c.complete('Done');
  var r = await c.future;
  print(r);
}

Expected output

Done

Questions and answers

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

1 Creating a Completer

Question
var c = ____<String>();
Answer
var c = Completer<String>();

Explanation: Completer<String>() creates a manually managed Future.

2 Which method is called to complete a Completer?

main.dart
var c = Completer<String>();
c.???('Done');
  • then
  • complete Correct answer
  • wait
  • close

Explanation: the complete method gives the Future a value and finishes it.

3 Match the Completer parts

Term Meaning
Completer<String>() Creation
c.complete('Done') Completion
c.future Future access
await c.future Waiting

All lessons in Intermediate