flutter 标准库中 GestureDetector
是不支持连点的,但是现在有需要用,怎么整呢,那就在 GestureDetector
基础上封装一个好了😄
import 'package:flutter/material.dart';
// 连点手势
class ContinuousTapGestureDetector extends GestureDetector {
final Widget child;
final ContinuousTapListener listener; // 连点监听者
ContinuousTapGestureDetector({@required this.child, @required this.listener}) : super(child: child, onTap: () {
listener.onTapListening();
});
}
class ContinuousTapListener {
final int numberOfTapsRequired; // 需要连点的次数, 默认为 1 次
final void Function() onContinuousTap; // 满足连点条件时的回调
int _lastTapTime = 0; // 上一次点击的时间戳
int _numberOfTapRecorded = 0; // 已记录的点击次数
int _maxMillisecondsBetweenTwoTaps = 350;// 两次点击的最大时间间隔
ContinuousTapListener({this.numberOfTapsRequired = 1, this.onContinuousTap});
void onTapListening() {
final now = DateTime.now().millisecondsSinceEpoch;
if (_lastTapTime > 0 && now - _lastTapTime > _maxMillisecondsBetweenTwoTaps) {
_resetRecord(time: now, count: 1);
} else {
_lastTapTime = now;
_numberOfTapRecorded += 1;
_checkAvailable();
}
}
// 重置记录
void _resetRecord({int time = 0, int count = 0}) {
_lastTapTime = time;
_numberOfTapRecorded = count;
}
// 验证是否满足预设条件,如果满足则执行回调函数
void _checkAvailable() {
if (_numberOfTapRecorded >= numberOfTapsRequired) {
_resetRecord();
if (onContinuousTap != null) {
onContinuousTap();
}
}
}
}
使用也比较简单
ContinuousTapGestureDetector(
child: Text('点点点'),
listener: ContinuousTapListener(
numberOfTapsRequired: 8,
onContinuousTap: () {
Get.toNamed(AppPages.APP_ENV);
},
),
),