Page 14 - Dart Language
P. 14
See example on Dartpad: https://dartpad.dartlang.org/11d189b51e0f2680793ab3e16e53613c
Converting callbacks to Futures
Dart has a robust async library, with Future, Stream, and more. However, sometimes you might
run into an asynchronous API that uses callbacks instead of Futures. To bridge the gap between
callbacks and Futures, Dart offers the Completer class. You can use a Completer to convert a
callback into a Future.
Completers are great for bridging a callback-based API with a Future-based API. For example,
suppose your database driver doesn't use Futures, but you need to return a Future. Try this code:
// A good use of a Completer.
Future doStuff() {
Completer completer = new Completer();
runDatabaseQuery(sql, (results) {
completer.complete(results);
});
return completer.future;
}
If you are using an API that already returns a Future, you do not need to use a Completer.
Read Asynchronous Programming online: https://riptutorial.com/dart/topic/2520/asynchronous-
programming
https://riptutorial.com/ 9

