gpt4 book ai didi

flutter - 嵌套的 GestureDetector OnTap 函数

转载 作者:行者123 更新时间:2023-12-04 11:31:17 25 4
gpt4 key购买 nike

我已经嵌套 GestureDetetor但问题是只有 child GestureDetectoronTap被执行。我不想覆盖 child 的 onTap,相反,我希望 parent 和 child 的 onTap 都执行。这是我的代码:

    GestureDetector(
onTap: () {
todo1();
},
child: GestureDetector(
onTap: () {
todo2();
},
child: Text("Nested Gesture")))
我如何更改它以同时调用 todo1()todo2()点按?
编辑:子项是一个可重用的自定义小部件,它有自己的实现,但现在被父项使用,除了它的子项之外,父项也有自己的实现

最佳答案

我制作了一个快速自定义手势识别器 - 只有当用户从初始点击点移动得太远时它才会取消手势。

用法示例:

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';

关于flutter - 嵌套的 GestureDetector OnTap 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56166994/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com