Dart 使用 .listen().onError().onDone() 流错误

Ben*_*enH 3 dart

我有一些看起来像这样的代码的问题。在这个表格中我有一个错误

The expression here has a type of 'void', and therefore can't be used. Try checking to see if you're using the correct API; there might be a function or call that returns void you didn't expect. Also check type parameters and variables which might also be void.dart(use_of_void_result).

如果我删除 .onDone() 错误就会消失。为什么?请 ELI5 :-) 我正在查看https://api.dart.dev/stable/2.7.0/dart-async/Stream/listen.html但似乎仍然误解了一些东西。我还阅读了https://api.dart.dev/stable/2.7.0/dart-async/StreamSubscription/onDone.html

serviceName.UploadThing(uploadRequest).listen((response) {
  uploadMessageOutput = response.message;
  if (response.uploadResult) {
    showSuccess();
  } else {
    showError();
  }
  getUploadFileList(event);

  isSaveInProgress = false;
}).onError((error) {
  isSaveInProgress = false;
  _handleFileUploadError(uploadRequest, error);
}).onDone(() {
  isSaveInProgress = false;
});
Run Code Online (Sandbox Code Playgroud)

Ben*_*nyi 8

您的代码几乎是正确的,但只需要进行简单的更改即可正常工作。

如果您交换onErrorand的顺序,您将看到相同的错误onDone,因此该问题与您的流使用无关。但是,您试图将调用链接在一起onError,然后onDone这将不起作用,因为这两个方法都返回void

什么你要找的是级联符号(..),这将允许您链调用到StreamSubscription由返回listen()。你的代码应该是这样的:

serviceName.UploadThing(uploadRequest).listen((response) {
  uploadMessageOutput = response.message;
  if (response.uploadResult) {
    showSuccess();
  } else {
    showError();
  }
  getUploadFileList(event);

  isSaveInProgress = false;
})..onError((error) { // Cascade
  isSaveInProgress = false;
  _handleFileUploadError(uploadRequest, error);
})..onDone(() {       // Cascade
  isSaveInProgress = false;
});
Run Code Online (Sandbox Code Playgroud)