Search code examples
buttonfluttergesture

How can I achieve "onContinuousPress" like behaviour?


Let's say that I have this button somewhere in my Flutter app:

FloatingActionButton(
 backgroundColor: Theme.of(context).primaryColor,
 child: Icon(Icons.arrow_upward),
 onPressed: _someAction,
);

I want that _someAction() will be executed as long as my finger is tapping on the button (i.e. if I tap continuously for T seconds _someAction() should be execute N times,

where N=(int)(60/T + 1))

I looked into GestureDetector but couldn't find what I need there. I need this for example in order to increase/decrease some int value...


Solution

  • int _value = 0;
    Timer _timer;
    
    Widget build(BuildContext context) {
      return GestureDetector(
        onTapDown: (details) => _startTimer(true),
        onTapUp: (details) => _startTimer(false),
        child: FlutterLogo(size: 200),
      );
    }
    
    void _startTimer(bool start) {
      if (!start) {
        _timer.cancel();
        return;
      }
      // you can adjust the timings here
      _timer = Timer.periodic(Duration(milliseconds: 1), (_) => _myMethod());
    }
    
    // this method will be getting called as long as you hold
    void _myMethod() => print("value = ${++_value}");