completeError method

  1. @override
void completeError(
  1. Object error, [
  2. StackTrace? stackTrace
])
override

Complete future with an error.

Calling complete or completeError must be done at most once.

Completing a future with an error indicates that an exception was thrown while trying to produce a value.

If error is a Future, the future itself is used as the error value. If you want to complete with the result of the future, you can use:

thisCompleter.complete(theFuture)

or if you only want to handle an error from the future:

theFuture.catchError(thisCompleter.completeError);

The future must have an error handler installed before the call to completeError) or error will be considered an uncaught error.

void doStuff() {
  // Outputs a message like:
  // Uncaught Error: Assertion failed: "future not consumed"
  Completer().completeError(AssertionError('future not consumed'));
}

You can install an error handler through Future.catchError, Future.then or the await operation.

void doStuff() {
  final c = Completer();
  c.future.catchError((e) {
    // Handle the error.
  });
  c.completeError(AssertionError('future not consumed'));
}

See the Zones article for details on uncaught errors.

Implementation

@override
void completeError(Object error, [StackTrace? stackTrace]) {
  assert(
      _isStarted == true, "Completing a future that hasn't been started...");
  if (!_delegate.isCompleted) _delegate.completeError(error, stackTrace);
}