How to set the duration of onLongPress Flutter

Viewed 2557

I know onLongPress would trigger after a certain period of time(like 500 ms or so). But what I want to do is to trigger some action when user presses the button for like 3 seconds. Actually I want to set the duration for onLongPress.

ElevatedButton(
  onPressed: () => print('ok I\'m just fine'),
  onLongPress: () => print('Trigger me when user presses me for like 3 seconds'),
  style: ElevatedButton.styleFrom(
  primary: Colors.red,
  elevation: 4,
),
3 Answers

How I did it:

onLongPress: () {
                Timer(Duration(milliseconds: (longPressIncrementDuration > 500) ? longPressIncrementDuration - 500 : 0), //enter function here//);

// I subtract 500 ms from required time limit as longpress on flutter activates after 500ms
              },

You can solve your problem this way, use onPanCancel and onPanDown of GestureDetector with timer.

class _MyHomePageState extends State<MyHomePage> {
  Timer _timer;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      floatingActionButton: GestureDetector(
        onPanCancel: () => _timer?.cancel(),
        onPanDown: (_) => {
          _timer = Timer(Duration(seconds: 3), () { // time duration
            // your function here
          })
        },
      ),
    );
  }
}

let me know if it work for you.

Related