flutter - 嵌套 GestureDetector OnTap 函数
问题描述
我嵌套GestureDetetor
了 s 但问题是只有 childGestureDetector
的onTap
被执行。我不希望覆盖孩子的 onTap,而是希望父母和孩子的 onTap 都执行。这是我的代码:
GestureDetector(
onTap: () {
todo1();
},
child: GestureDetector(
onTap: () {
todo2();
},
child: Text("Nested Gesture")))
如何将其更改为同时调用todo1()
和todo2()
onTap?
编辑:孩子是一个可重用的自定义小部件,它有自己的实现,但现在被父母使用,除了它的孩子之外,它也有自己的实现
解决方案
我制作了一个快速的自定义手势识别器 - 只有当用户距离初始点击点太远时它才会取消手势。
使用示例:
UniversalTapHandler(
onTap: () {
print("Tap 1");
},
child: UniversalTapHandler(
onTap: () {
print("Tap 2");
},
child: Text("Nested Gesture"),
)
)
源代码:
class UniversalTapHandler extends RawGestureDetector {
UniversalTapHandler({
@required GestureTapCallback onTap,
@required Widget child,
}):
super(
gestures: <Type, GestureRecognizerFactory>{
_UniversalPointerHandler: GestureRecognizerFactoryWithHandlers<_UniversalPointerHandler>(
() => _UniversalPointerHandler(onTap: onTap),
(_) {},
),
},
child: child,
);
}
class _UniversalPointerHandler extends OneSequenceGestureRecognizer {
_UniversalPointerHandler({
@required this.onTap,
}): super();
final GestureTapCallback onTap;
final _maxDistance = 18; // as in official recognizer by default
Offset _startPosition;
void _reset() {
_startPosition = null;
}
@override
void addPointer(PointerDownEvent event) {
_startPosition = event.position;
startTrackingPointer(event.pointer);
resolve(GestureDisposition.accepted);
}
@override
void handleEvent(PointerEvent event) {
if (event is PointerUpEvent) {
stopTrackingPointer(event.pointer);
if (_startPosition != null) {
onTap();
}
}
if (event is PointerMoveEvent && _startPosition != null) {
if ((event.position - _startPosition).distance > _maxDistance) {
rejectGesture(event.pointer);
_reset();
}
}
if (event is PointerCancelEvent || event is PointerExitEvent || event is PointerRemovedEvent) {
_reset();
}
}
@override
void resolve(GestureDisposition disposition) {
if (disposition == GestureDisposition.rejected) {
_reset();
}
super.resolve(disposition);
}
@override
void didStopTrackingLastPointer(int pointer) {}
@override
String get debugDescription => "_UniversalPointerHandler: Custom Gesture Recognizer";
}
更新 不要忘记导入这个:
import 'package:flutter/gestures.dart';
推荐阅读
- javascript - Vanilla Javascript 移除 Promise
- yii2 - 用户点击链接后显示页面,yii2应用程序不需要登录
- javascript - ? 没有 then 案例的操作员
- visual-studio-code - 什么设置导致 VS Code 在我粘贴时弄乱了代码格式?
- vue.js - 如何对 Vuetify 数据表中的列进行排序?
- time - 在 Anylogic 中测量汇编器元素中的时间,
- performancecounter - 如何将性能计数器传递给 SCOM Retrieve Performance Data Rest API?
- c# - 匹配 PHP 和 C# 加密/解密
- typescript - 打字稿,在“{}”类型上找不到带有“字符串”类型参数的索引签名
- python - 给定一个元组列表,说明它们的已知顺序,如何对 N 个元素进行排序?