未取消未来

Not canceled Future

我尝试取消Future,但仍然在.then()中获取执行代码。 为什么它不起作用,我做错了什么?

var c = CancelableOperation.fromFuture(
     Future.delayed(new Duration(seconds: 5), () {

     }).then((data){
       print("123"); // This code is always called...
     })

 );
 c.cancel();

https://pub.dartlang.org/packages/async

The CancelableOperation class defines an operation that can be canceled by its consumer. The producer can then listen for this cancellation and stop producing the future when it's received. It can be created using a CancelableCompleter.

尤其是这部分

The producer can then listen for this cancellation and stop producing

所以价值的生产者应该停止工作。这并不意味着它不会 return 结果。它可能 return null 表示它不是实际结果。

你想要的可能是CancelableCompleter

单元测试可能有助于理解这些类应该如何使用

https://github.com/dart-lang/async/blob/1106a5bfee1472905711da7a78dcd413ba2f6dcf/test/cancelable_operation_test.dart#L93-L134(以及此文件中的其他内容)