You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

长按实现数值递增异常:长按仅触发一次递增回调

解决长按按钮持续触发递增的问题

你当前的IncrementButton在长按仅触发一次回调,是因为onLongPressStart只会在长按开始时执行一次。要实现长按持续触发,需要借助定时器周期性调用回调,同时要管理定时器的启动与销毁,具体修改如下:

修改后的IncrementButton代码

将原StatelessWidget改为StatefulWidget,添加定时器逻辑:

class IncrementButton extends StatefulWidget {
  final VoidCallback callback;
  // 可自定义长按触发的间隔时间,默认300ms
  final Duration interval;

  const IncrementButton({
    Key? key,
    required this.callback,
    this.interval = const Duration(milliseconds: 300),
  }) : super(key: key);

  @override
  State<IncrementButton> createState() => _IncrementButtonState();
}

class _IncrementButtonState extends State<IncrementButton> {
  Timer? _longPressTimer;

  @override
  void dispose() {
    // 页面销毁时取消定时器,避免内存泄漏
    _longPressTimer?.cancel();
    super.dispose();
  }

  void _startLongPressTimer() {
    // 启动周期性定时器,每隔指定间隔调用一次回调
    _longPressTimer = Timer.periodic(widget.interval, (timer) {
      widget.callback();
    });
  }

  void _stopLongPressTimer() {
    // 取消定时器
    _longPressTimer?.cancel();
    _longPressTimer = null;
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: widget.callback,
      onLongPressStart: (_) => _startLongPressTimer(),
      onLongPressEnd: (_) => _stopLongPressTimer(),
      onLongPressCancel: _stopLongPressTimer,
      // 这里保留你原来的按钮UI代码
      child: Container(
        padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 10),
        decoration: BoxDecoration(
          color: Colors.blue,
          borderRadius: BorderRadius.circular(8),
        ),
        child: const Text(
          "递增",
          style: TextStyle(color: Colors.white),
        ),
      ),
    );
  }
}

使用方式与原代码一致

IncrementButton(
  callback: _increment,
  // 可选:自定义间隔时间,比如200ms
  // interval: const Duration(milliseconds: 200),
),

注意事项

  • 你的_increment函数如果涉及UI更新,需要用setState包裹,确保数值变化能同步到界面:
    void _increment() {
      setState(() {
        value += 1;
      });
    }
    
  • 定时器的间隔时间可以根据需求调整,间隔越短,递增速度越快。

内容的提问来源于stack exchange,提问作者Arnob

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 16:51:33