flutterdartdart-async

is there any way to cancel a dart Future?


In a Dart UI, I have a button submit to launch a long async request. The submit handler returns a Future. Next, the button submit is replaced by a button cancel to allow the cancellation of the whole operation. In the cancel handler, I would like to cancel the long operation. How can I cancel the Future returned by the submit handler? I found no method to do that.


Solution

  • As far as I know, there isn't a way to cancel a Future. But there is a way to cancel a Stream subscription, and maybe that can help you.

    Calling onSubmit on a button returns a StreamSubscription object. You can explicitly store that object and then call cancel() on it to cancel the stream subscription:

    StreamSubscription subscription = someDOMElement.onSubmit.listen((data) {
    
       // you code here
    
       if (someCondition == true) {
         subscription.cancel();
       }
    });
    

    Later, as a response to some user action, perhaps, you can cancel the subscription: