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

2020-05-24 19:01发布

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);

}

4条回答
相关推荐>>
2楼-- · 2020-05-24 19:52

@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>>();

查看更多
▲ chillily
3楼-- · 2020-05-24 19:52

Or you can mark it as an async method:

Future<String> myFutureMethod() async {

  // do something that takes a while

  return 'done';
}
查看更多
该账号已被封号
4楼-- · 2020-05-24 19:56

You can simply use the Future<T>value factory constructor:

return Future<String>.value('Back to the future!');
查看更多
你好瞎i
5楼-- · 2020-05-24 20:08

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.

查看更多
登录 后发表回答