Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/dart/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Dart 使用Futures时.then()和.whenCompleted()方法之间的区别?_Dart - Fatal编程技术网

Dart 使用Futures时.then()和.whenCompleted()方法之间的区别?

Dart 使用Futures时.then()和.whenCompleted()方法之间的区别?,dart,Dart,我正在探索Dart的未来,我对未来提供的这两种方法感到困惑,.then()和.whenCompleted()。他们之间的主要区别是什么 假设我想使用.readAsString()读取.txt,我会这样做: void main(){ File file = new File('text.txt'); Future content = file.readAsString(); content.then((data) { print(content); }); } 因此,

我正在探索Dart的未来,我对未来提供的这两种方法感到困惑,
.then()
.whenCompleted()
。他们之间的主要区别是什么

假设我想使用
.readAsString()
读取.txt,我会这样做:

void main(){
  File file = new File('text.txt');
  Future content = file.readAsString();
  content.then((data) {
    print(content);
  });  
}
因此,
.then()
就像一个回调函数,一旦将来完成,它就会触发一个函数

但我看到还有
.whenComplete()
,它也可以在Future完成后启动函数。大概是这样的:

void main(){
  File file = new File('text.txt');
  Future content = file.readAsString();
  content.whenComplete(() {
    print("Completed");
  });
}
我在这里看到的区别是,
.then()
可以访问返回的数据!
.whenCompleted()
用于什么?什么时候我们应该选择一个而不是另一个?

将在Future完成并没有错误时启动函数,而将在Future完成且没有错误时启动函数

引用API文档

这是“finally”块的异步等价物


.whenComplete
=此将来完成时调用
.whenComplete
中的函数,无论是使用值还是使用错误

。然后
=返回一个新的Future,该Future通过调用onValue(如果此Future通过值完成)或onError(如果此Future通过错误完成)的结果完成

阅读API文档的详细信息


即使有错误,
也可以调用
,前提是您指定了
catchError

someFuture.catchError(
  (onError) {
    print("called when there is an error catches error");
  },
).then((value) {
  print("called with value = null");
}).whenComplete(() {
  print("called when future completes");
});

因此,如果出现错误,将调用上述所有回调

它们不是真正的类型,但实际上不是。。。如果将
然后
放在
catchError
之后,则调用
然后
,因为
catchError
返回一个全新的未来,事实上,如果在
catchError
中返回一个错误,则不会触发
,在异步代码中,您的代码如下所示: