飞镖,如何在自己的功能中创造未来?

时间:2013-08-24 22:17:29

标签: asynchronous dart future

是否可以在Dart中创建自己的未来以从您的方法返回,或者您是否必须始终从其中一个dart异步库方法返回内置的未来返回值?

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

List<Base> aListOfItems = ...;

Future<List<Base>> GetItemList(){

    return new Future(aListOfItems);

}

5 个答案:

答案 0 :(得分:42)

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

Future<List<Base>> GetItemList(){
  var completer = new Completer();

  // At some time you need to complete the future:
  completer.complete(new List<Base>());

  return completer.future;
}

但大多数时候你不需要用完成者来创造未来。就像在这种情况下:

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

Future<List<Base>> GetItemList(){
  return aFuture.then((a) {
    // Do something..
  });
}

或者文件io的示例:

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

有关更多提示,请参阅this blog post

答案 1 :(得分:5)

@ Fox32有正确的答案,我们需要提到完成者的类型,否则我们会得到异常

Exception received is type 'Future<dynamic>' is not a subtype of type 'FutureOr<List<Base>>

所以完成者的初始化将成为

var completer= new Completer<List<Base>>();

答案 2 :(得分:3)

您可以简单地使用Future<T>value工厂构造函数:

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

答案 3 :(得分:2)

或者您可以将其标记为async方法:

Future<String> myFutureMethod() async {

  // do something that takes a while

  return 'done';
}

答案 4 :(得分:0)

不完全是给定问题的答案,但有时我们可能想要await一个闭包:

    flagImage ??= await () async {
      ...
      final image = (await codec.getNextFrame()).image;
      return image;
    }();

我认为它确实隐含地创造了一个未来,即使我们没有在任何地方传递它。

相关问题