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

后端 未结 4 870
抹茶落季
抹茶落季 2021-02-01 00:27

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?

4条回答
  •  逝去的感伤
    2021-02-01 01:18

    If you need to create a future, you can use a Completer. See Completer class in the docs. Here is an example:

    Future> GetItemList(){
      var completer = new Completer>();
    
      // At some time you need to complete the future:
      completer.complete(new List());
    
      return completer.future;
    }
    

    But most of the time you don't need to create a future with a completer. Like in this case:

    Future> 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> GetItemList(){
      return aFuture.then((a) {
        // Do something..
      });
    }
    

    Or an example for file io:

    Future> readCommaSeperatedList(file){
      return file.readAsString().then((text) => text.split(','));
    }
    

    See this blog post for more tips.

提交回复
热议问题