throttledGesture_gesture_detector.dart
1015 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
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,
);
}
}