Dart completer

Easy example of Dart completer

What is a completer?

How to generate Future objects and complete them later using values ​​or errors

When to use them?

When it is necessary to create a Future from scratch
(for example, when converting a callback-based API to a Future-based API)
*Callback function: A function passed as an argument to a function

First, create a Completer object.
Next, by performing asynchronous processing and calling Completer’s complete(T value) method within it, you can complete the processing of the corresponding Future.
Then, the future object of Completer is returned as the return value.
Finally, if the caller processes the Future, the asynchronous process is complete. Now we can implement an asynchronous method.

import 'dart:async';

main() {
  asyncMethod().then((message) => print(message));
}

Future<String> asyncMethod() {
  
  //Create Completer<T>
  var completer = new Completer<String>();
  
  // When some asynchronous process is completed
  // Call Completer<T>'s complete<T value> method to complete the process
  new Timer(new Duration(seconds: 1), () => completer.complete("done."));
  
  // Returns the Future object of Completer
  return completer.future;
}

Have any Question or Comment?

Leave a Reply

Your email address will not be published. Required fields are marked *