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

混江龙づ霸主 提交于 2020-02-17 18:02:39

问题


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

}

回答1:


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.




回答2:


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

return Future<String>.value('Back to the future!');



回答3:


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




回答4:


Or you can mark it as an async method:

Future<String> myFutureMethod() async {

  // do something that takes a while

  return 'done';
}


来源:https://stackoverflow.com/questions/18423691/dart-how-to-create-a-future-to-return-in-your-own-functions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!