Dart,如何创造一个未来来回归自己的​​职能? [英] Dart, how to create a future to return in your own functions?

查看:55
本文介绍了Dart,如何创造一个未来来回归自己的​​职能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能在Dart中创建自己的期货以从您的方法中返回,还是必须始终从dart异步库方法之一返回内置的未来收益?

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?

我想定义一个始终返回Future<List<Base>>的函数,无论它实际上是在进行异步调用(文件读取/ajax/etc)还是仅获取局部变量,如下所示:

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

}

推荐答案

如果需要创建未来,可以使用Completer.请参阅文档中的 Completer.这是一个示例:

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

使用完成程序,代码可能变得非常复杂.您可以简单地使用以下内容,因为then()也会返回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..
  });
}

或者是文件io的示例:

Or an example for file io:

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

请参见此博客文章有关更多提示.

这篇关于Dart,如何创造一个未来来回归自己的​​职能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆