It’s not enough for Flutter to know the Future, you also need the Completer

Completer is a way of creating a Future, creating a Future internally and allowing you to actively complete it after a period of time. In general, if your asynchronous operation is of a call-back type that doesn’t return results immediately, you need to use Completer.

Most of the time, the easiest way to create a Future is directly through its constructor to capture the result of an asynchronous computation:

new Future(() { doSomething(); return result; });
Copy the code

Or, future.then handles a series of asynchronous operations:

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

However, if your calculation is performed with a callback method, the above method will not work. You need to use Completer to create:

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); }}Copy the code

To use Completer, you only need these three steps:

  1. createCompleter
  2. theCompleter.futuredistributed
  3. callcompleter.completeorcompleter.completeError
var completer = new Completer();
handOut(completer.future);
later: {
  completer.complete('completion value');
}
Copy the code

The typical object constructed with Completer() is an instance of _AsyncCompleter, whose complete method is asynchronous, meaning that callbacks registered in the future will not execute immediately, but will be deferred to the next microtask.

If you have a special need to complete synchronization, you need to construct it using the completer. sync method, which takes an instance of the _SyncCompleter object.