Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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);  } 
like image 967
Daniel Robinson Avatar asked Aug 24 '13 22:08

Daniel Robinson


People also ask

How do you create a Future function in darts?

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.

How do you initialize a Future in Flutter?

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 .

How do you wait for Future to complete Dart?

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.


1 Answers

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.

like image 93
Fox32 Avatar answered Sep 28 '22 20:09

Fox32