Check how long was a button pressed in Flutter
778
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');
}
}
Author by
Abel Herlambang
Updated on December 04, 2022Comments
-
Abel Herlambang over 1 year
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.
-
Abel Herlambang over 3 yearsUh apparently it does work but, if I unpress it earlier than 1000 milliseconds it'll still run the function. So it's still not really working properly.
-
Jigar Patel over 3 yearsare you sure? I checked that case too. And it did not call the function if I unpress it earlier. Because when we unpress,
onTapUp
is called and so timer is cancelled. -
Abel Herlambang over 3 yearsOh yeah, it's working. Apparently, it's my fault that I declared the Timer in the wrong place smh. Thanks again.