throttledGesture_gesture_detector.dart 1015 Bytes
import 'dart:async';
import 'package:flutter/material.dart';

///带节流功能的GestureDetector
class ThrottledGestureDetector extends StatefulWidget {
  final Widget child;
  final VoidCallback? onTap;
  final int throttleTime;

  const ThrottledGestureDetector({
    super.key,
    required this.child,
    required this.onTap,
    this.throttleTime = 500, // 默认节流时间为500毫秒
  });

  @override
  _ThrottledGestureDetectorState createState() =>
      _ThrottledGestureDetectorState();
}

class _ThrottledGestureDetectorState extends State<ThrottledGestureDetector> {
  bool _isThrottled = false;

  void _handleTap() {
    if (!_isThrottled) {
      if (widget.onTap != null) {
        widget.onTap!();
      }
      _isThrottled = true;
      Timer(Duration(milliseconds: widget.throttleTime), () {
        _isThrottled = false;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: _handleTap,
      child: widget.child,
    );
  }
}