我嵌套了GestureDetetor
,但是问题是只有子GestureDetector
的{{1}}被执行。我不想覆盖孩子的onTap,而是希望父母和孩子的onTap都执行。这是我的代码:
onTap
如何更改此名称以同时调用 GestureDetector(
onTap: () {
todo1();
},
child: GestureDetector(
onTap: () {
todo2();
},
child: Text("Nested Gesture")))
和todo1()
onTap?
答案 0 :(得分:0)
我做了一个快速的自定义手势识别器-仅当用户距离初始点击点太远时,它才会取消手势。
用法示例:
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';
答案 1 :(得分:0)
您可以在嵌套的 onTap 回调中调用 todo1():
GestureDetector(
onTap: () {
todo1();
},
child: GestureDetector(
onTap: () {
todo2();
todo1();
},
child: Text("Nested Gesture")))