is there any way to cancel a dart Future?

后端 未结 9 1447
礼貌的吻别
礼貌的吻别 2020-11-27 05:55

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 a

相关标签:
9条回答
  • 2020-11-27 06:21

    my 2 cents worth...

    class CancelableFuture {
      bool cancelled = false;
      CancelableFuture(Duration duration, void Function() callback) {
        Future<void>.delayed(duration, () {
          if (!cancelled) {
            callback();
          }
        });
      }
    
      void cancel() {
        cancelled = true;
      }
    }
    
    0 讨论(0)
  • 2020-11-27 06:21

    How to cancel Future.delayed

    A simple way is to use Timer instead :)

    Timer _timer;
    
    void _schedule() {
      _timer = Timer(Duration(seconds: 2), () { 
        print('Do something after delay');
      });
    }
    
    @override
    void dispose() {
      super.dispose();
      _timer?.cancel();
    }
    
    0 讨论(0)
  • 2020-11-27 06:22

    One way I accomplished to 'cancel' a scheduled execution was using a Timer. In this case I was actually postponing it. :)

    Timer _runJustOnceAtTheEnd;
    
    void runMultipleTimes() {
      _runJustOnceAtTheEnd?.cancel();
      _runJustOnceAtTheEnd = null;
    
      // do your processing
    
      _runJustOnceAtTheEnd = Timer(Duration(seconds: 1), onceAtTheEndOfTheBatch);
    }
    
    void onceAtTheEndOfTheBatch() {
      print("just once at the end of a batch!");
    }
    
    
    runMultipleTimes();
    runMultipleTimes();
    runMultipleTimes();
    runMultipleTimes();
    
    // will print 'just once at the end of a batch' one second after last execution
    

    The runMultipleTimes() method will be called multiple times in sequence, but only after 1 second of a batch the onceAtTheEndOfTheBatch will be executed.

    0 讨论(0)
提交回复
热议问题