dart 如何设置onLongPress的持续时间

tquggr8v  于 2022-12-20  发布在  其他
关注(0)|答案(4)|浏览(428)

我知道onLongPress会在一段时间后触发(比如500毫秒左右)。但是我想做的是当用户按下按钮3秒时触发一些动作。实际上我想设置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,
),
bgtovc5b

bgtovc5b1#

我是怎么做到的:

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
              },
wnvonmuf

wnvonmuf2#

您可以通过这种方式解决问题,使用带有计时器的GestureDetector的onPanCancel和onPanDown。

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
          })
        },
      ),
    );
  }
}

让我知道它是否适合你。

gstyhher

gstyhher3#

我今天做了一个包,你可以设置手势检测器的持续时间。如果你想,你可以试试https://pub.dev/packages/custom_long_tap

hjzp0vay

hjzp0vay4#

GestureDetector(
      onTapDown: (_) { //Detect when you click the element
        _timer = Timer(
          const Duration(seconds: 5),
          () {
            Navigator.push(
              context,
              MaterialPageRoute(
                builder: (context) => const ListOrder(),
              ),
            );
          },
        );
        print('tapping');
      },
      onTapUp: (_) { // Detect and cancel when you lift the click
        _timer!.cancel();
        print('cancel');
      },
      child: const Icon(Icons.person_search),
),

相关问题