Check how long was a button pressed in Flutter

Viewed 705

I'm actually currently using Division for handling the gestures of buttons. But I'm still finding a way to do it with and without division. I wanted the long press of the button to be launched after 1000 milliseconds instead of 500.

I've searched on SO and other sites but still can't seem to find the solution of this exact problem.

This is how it work with Division. I've tried to use while and Future.delayed but can't seem to make it work properly. But it's totally fine if it's not in Division's Gesture(). Because I just wanted this to work properly regardless if it's using Division or not.

Gestures()
          ..isTap((isTapped) => setState(() => pressed = isTapped))
          ..onLongPress(() { print("long pressed"); })

Thank you in advance.

2 Answers

One way you can do this is something like this using a Timer from dart:async

class _MyWidgetState extends State<MyWidget> {
  
  Timer timer;
  
  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTapDown: (_) {
        timer = Timer(Duration(milliseconds: 1000), onLongerPress);
      },
      onTapUp: (_){
        timer.cancel();
      },
      child: Container(child: Center(child: Text('Click here')), width: 200, height: 50, color: Colors.green),
    );
  }
  
  void onLongerPress() {
    print('onLongerPress called');
  }
  
}

you can use from this code

 GestureDetector(
    onLongPress: () {
      setState(() {
        _lights = true;
      });
    },
 );
Related