W3cubDocs

/Dart 2

Completer<T> class

A way to produce Future objects and to complete them later with a value or error.

Most of the time, the simplest way to create a future is to just use one of the Future constructors to capture the result of a single asynchronous computation:

new Future(() { doSomething(); return result; });

or, if the future represents the result of a sequence of asynchronous computations, they can be chained using Future.then or similar functions on Future:

Future doStuff(){
  return someAsyncOperation().then((result) {
    return someOtherAsyncOperation(result);
  });
}

If you do need to create a Future from scratch — for example, when you're converting a callback-based API into a Future-based one — you can use a Completer as follows:

class AsyncOperation {
  Completer _completer = new Completer();

  Future<T> doOperation() {
    _startOperation();
    return _completer.future; // Send future object back to client.
  }

  // Something calls this when the value is ready.
  void _finishOperation(T result) {
    _completer.complete(result);
  }

  // If something goes wrong, call this.
  void _errorHappened(error) {
    _completer.completeError(error);
  }
}

Constructors

Completer()
factory
Creates a new completer. [...]
Completer.sync()
factory
Completes the future synchronously. [...]

Properties

futureFuture<T>
read-only
The future that is completed by this completer. [...]
isCompletedbool
read-only
Whether the future has been completed. [...]
hashCodeint
read-only, inherited
The hash code for this object. [...]
runtimeTypeType
read-only, inherited
A representation of the runtime type of the object.

Methods

complete([FutureOr<T> value ]) → void
Completes future with the supplied values. [...]
completeError(Object error, [ StackTrace stackTrace ]) → void
Complete future with an error. [...]
noSuchMethod(Invocation invocation) → dynamic
inherited
Invoked when a non-existent method or property is accessed. [...]
toString() → String
inherited
Returns a string representation of this object.

Operators

operator ==(dynamic other) → bool
inherited
The equality operator. [...]

© 2012 the Dart project authors
Licensed under the Creative Commons Attribution-ShareAlike License v4.0.
https://api.dartlang.org/stable/2.0.0/dart-async/Completer-class.html