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

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

List<Base> aListOfItems = ...;

Future<List<Base>> GetItemList(){

    return new Future(aListOfItems);

}

推荐答案

如果你需要创造future ,你可以使用Completer.请参见文档中的Completer class.下面是一个示例:

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

但大多数情况下,你不需要用完成者来创造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.

Dart相关问答推荐

播放和暂停 Flutter 动画

停止在缓存中保存 Flutter Web Firebase 托管

MappedListIterable 不是子类型

Flutter/Dart:子类化冻结的数据类

我可以动态应用 Dart 的字符串插值吗?

执行 `dart2js` 时会生成哪些文件?为什么?

如何使用 Android aar 文件构建 Flutter 项目?

InheritedWidget - 在 navigator.push 之后在 null 上调用 getter

如何在 Flutter 中忽略整个文件的 lint 规则?

如何处理 ListView 滚动方向

如何在Flatter中打开设备GPS?

Expansion Panel底部溢出

如何在 Dart 中替换字符串中间的空格?

如何在 Visual Studio Code 中禁用fake右括号注释?

Dart:并行处理传入的 HTTP 请求

从 Dart 调用 javascript

你如何命名一个 Dart 类?

Dart - 如何对 Map 的键进行排序

如何展平flatten列表?

Dart null / false / empty checking:如何写这个更短?