Dart, how to create a future to return in your own functions?

Daniel Robinson picture Daniel Robinson · Aug 25, 2013 · Viewed 27k times · Source

is it possible to create your own futures in Dart to return from your methods, or must you always return a built in future return from one of the dart async libraries methods?

I want to define a function which always returns a Future<List<Base>> whether its actually doing an async call (file read/ajax/etc) or just getting a local variable, as below:

List<Base> aListOfItems = ...;

Future<List<Base>> GetItemList(){

    return new Future(aListOfItems);

}

Answer

Fox32 picture Fox32 · Aug 25, 2013

If you need to create a future, you can use a Completer. See Completer class in the docs. Here is an example:

Future<List<Base>> GetItemList(){
  var completer = new Completer<List<Base>>();

  // At some time you need to complete the future:
  completer.complete(new List<Base>());

  return completer.future;
}

But most of the time you don't need to create a future with a completer. Like in this case:

Future<List<Base>> GetItemList(){
  var completer = new Completer();

  aFuture.then((a) {
    // At some time you need to complete the future:
    completer.complete(a);
  });

  return completer.future;
}

The code can become very complicated using completers. You can simply use the following instead, because then() returns a Future, too:

Future<List<Base>> GetItemList(){
  return aFuture.then((a) {
    // Do something..
  });
}

Or an example for file io:

Future<List<String>> readCommaSeperatedList(file){
  return file.readAsString().then((text) => text.split(','));
}

See this blog post for more tips.