Completer pattern in Dart

Sometimes you want to halt the execution of a code block until you signal it to proceed further. Dart provides the Completer class for this purpose.

The Completer class is a convenient way to create a future and later complete it with a value or error. The completer completes the future asynchronously as you signal it from some other location in your code block.

The following example shows how to use a Completer:

import 'dart:async';

void main() async {
  final shouldEnterHouse = Completer<bool>();

  print('awaiting to enter the house :)');
  _allowEntryAfterTwoSecs(shouldEnterHouse);

  final result = await _getResult(shouldEnterHouse);
  print(result);
}

Future<String> _getResult(Completer<bool> shouldEnterHouse) {
  const successString = 'I\'ve entered the house :)';
  const errorString = 'Couldn\'t enter the house :(';

  return shouldEnterHouse.future.then((value) {
    if (value) {
      return successString;
    } else {
      return errorString;
    }
  }).catchError(
    (e, s) => errorString,
  );
}

void _allowEntryAfterTwoSecs(Completer<bool> shouldEnterHouse) {
  Future.delayed(const Duration(seconds: 2), () {
    shouldEnterHouse.complete(true);
    // shouldEnterHouse.completeError(Exception('error'));
  });
}

Here we are waiting to enter the house. We are using a Completer to complete the future after two seconds. And we are able to signal the future to complete with a value or error from anywhere in the code using the instance of Completer.

0
Subscribe to my newsletter

Read articles from NonStop io Technologies directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

NonStop io Technologies
NonStop io Technologies

Product Development as an Expertise Since 2015 Founded in August 2015, we are a USA-based Bespoke Engineering Studio providing Product Development as an Expertise. With 80+ satisfied clients worldwide, we serve startups and enterprises across San Francisco, Seattle, New York, London, Pune, Bangalore, Tokyo and other prominent technology hubs.