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); }
Dart future simple example Since in the main function we work with futures, we mark it with the async keyword. var myfut1 = Future. value(14); print(myfut1); This code is incorrect; we create a new future with Future.
One way is to make _future nullable and to make your asynchronous function idempotent by checking if _future is null . If it's null, do work; if it's not null, then just return the existing Future .
To prevent multiple awaits, chaining futures in . then(), you can simply use Future. wait([]) that returns an array of results you were waiting for. If any of those Futures within that array fails, Future.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With