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);
}
@Fox32 has the correct answer addition to that we need to mention Type of the Completer otherwise we get exception
Exception received is type 'Future<dynamic>' is not a subtype of type 'FutureOr<List<Base>>
so initialisation of completer would become
var completer= new Completer<List<Base>>();
Or you can mark it as an
async
method:You can simply use the
Future<T>value
factory constructor:If you need to create a future, you can use a
Completer
. SeeCompleter
class in the docs. Here is an example:But most of the time you don't need to create a future with a completer. Like in this case:
The code can become very complicated using completers. You can simply use the following instead, because
then()
returns aFuture
, too:Or an example for file io:
See this blog post for more tips.