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

Mat*_*ija 3 dart

我正在探索Dart中的Futures,并且对Future提供的这两种方法感到困惑。它们之间的主要区别是什么?

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

void main(){
  File file = new File('text.txt');
  Future content = file.readAsString();
  content.then((data) {
    print(content);
  });  
}
Run Code Online (Sandbox Code Playgroud)

因此.then(),就像Future完成后触发功能的回调一样。

但是我看到,.whenComplete()一旦Future完成,也可以触发功能。像这样的东西:

void main(){
  File file = new File('text.txt');
  Future content = file.readAsString();
  content.whenComplete(() {
    print("Completed");
  });
}
Run Code Online (Sandbox Code Playgroud)

我在这里看到的区别是可以.then()访问返回的数据!有什么.whenCompleted()用?什么时候选择一个?

而且还这两个环节上,。那么().whenCompleted()在一个页面有实现的结尾:

。然后():

Future<R> then<R>(FutureOr<R> onValue(T value), {Function onError});
Run Code Online (Sandbox Code Playgroud)

.whenCompleted():

Future<T> whenComplete(FutureOr action());
Run Code Online (Sandbox Code Playgroud)

什么Future<R>意思 还是Future<T>?我知道Future是一种类型,但是R和T是什么?

谢谢!

Mat*_*tia 8

.whenComplete会在Future是否完成但没有错误时触发函数,而.then将在Future完成而没有错误时触发函数。

引用.whenComplete API DOC

这是“最终”块的异步等效项。

  • 实际上不是......如果你把 `then` 放在 `catchError` 之后,`then` 就会被调用,因为 `catchError` 返回一个全新的 Future,实际上,如果要在 `catchError` 中返回错误,`.then` 就不会被调用。触发,在异步代码中,您的代码将如下所示:https://gist.github.com/Hexer10/87a6f38616f74321c85f2f91a5450d4e (2认同)

iDe*_*ode 5

即使出现错误,then仍然可以调用,前提是您已指定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");
});
Run Code Online (Sandbox Code Playgroud)

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