0

I want to cancel a function before it reaches the end if I call stop().

class Example {
  late final completer = CancelableCompleter();
  final List<String> list;

  Example(this.list);

  void start() {
     completer.complete(doWork());
  }

  Future<void> doWork() async {
     for(final e in list) {
       await a();
       await b();
     }
     await c();
     print("end");
  }

   void stop() {
      completer.operation.cancel();
   }
}

I followed this is there any way to cancel a dart Future? but the execution stills happens.

Should I put a bunch of if(completer.isCancelled) before every await call that I make?

J_Strauton
  • 2,270
  • 3
  • 28
  • 70

1 Answers1

0

You can give cancelable completer a try

class MyPage extends StatelessWidget {
  final CancelableCompleter<bool> _completer = CancelableCompleter(onCancel: () => false);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        children: [
          TextButton(
            child: Text("Start future"),
            onPressed: () async {
              bool futureExecuted = await startFuture();
              print(futureExecuted);
            },
          ),
          TextButton(child: Text("Cancel future"), onPressed: cancelFuture),
        ],
      ),
    );
  }

  Future startFuture() async {   _completer.complete(Future.value(realFuture()));
    return _completer.operation.value;
  }


  Future realFuture() async {
    return await Future.delayed(Duration(seconds: 10), () => true);
  }

  void cancelFuture() async {
    var value = await _completer.operation.cancel();
    assert(value == false);
  }
}
Kaushik Chandru
  • 15,510
  • 2
  • 12
  • 30
  • Please help me understand. How does this make the future cancel? I see it very similar to my code above. – J_Strauton Aug 07 '22 at 16:41
  • Yes its much similar to your code but if you notice that on cancel i have returned a false. So the completer got the false as value and the code isnt executed after that. But if theres no return then i think it executes the future and returns the output of the future – Kaushik Chandru Aug 07 '22 at 17:07