5

how can i cancel Future.delayed

i am using Future.delayed for some task, but if i want to cancel this delayed task, so is their any method or any other things to use.

Future.delayed(Duration(seconds: 10),(){
  setState(() {
    //some method calling
  });
});
Deepak Gehlot
  • 2,661
  • 5
  • 21
  • 25

1 Answers1

2

what about declare a bool value

bool _executeFuture=true;

then

Future.delayed(Duration(seconds: 10),(){
if(_executeFuture){
  setState(() {
    //some method calling
  });
}
});

Now whenever you want to cancel Future just use

_executeFuture=false;

Also, You can use CancelableOperation from https://pub.dartlang.org/packages/async

Dev
  • 6,628
  • 2
  • 25
  • 34
  • Is this really cancelling the future or just not executing the code within? I feel like that is a pretty significant difference. – eimmer Jun 30 '21 at 13:21
  • It's just preventing the future code to be executed. Future will anyway run the code. As calling Future is an asynchronous and we do not get any reference for the called function so, the option remains just to prevent the code from being executed if it is no longer required. You can use You can use CancelableOperation from https://pub.dartlang.org/packages/async if needed – Dev Jun 30 '21 at 15:11