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?>
If you need to create a future, you can use a Completer
. See Completer class in the docs. Here is an example:
Future> GetItemList(){
var completer = new Completer>();
// At some time you need to complete the future:
completer.complete(new List ());
return completer.future;
}
But most of the time you don't need to create a future with a completer. Like in this case:
Future> 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> GetItemList(){
return aFuture.then((a) {
// Do something..
});
}
Or an example for file io:
Future> readCommaSeperatedList(file){
return file.readAsString().then((text) => text.split(','));
}
See this blog post for more tips.