检测指针的位置是否在Widget内部或不在PointerUp事件上



我正在创建一个行为像按钮的小部件,我想让它知道当触摸解除时触摸点是否在它之外,就像这样。有什么想法吗?

Listener(
onPointerMove: (event) {
},
onPointerDown: (event) {
},
onPointerUp: (event) {
//Detect if the position of the pointer is still inside or not
},
child: Container(
width: 200, height: 200,
),
)

您可以使用GestureDetector来监听拖动事件,这将为您提供指针的确切位置(当按下指针时(,并将其与小部件的大小进行比较(您可以通过向小部件本身添加一个键来获得(。

以下是一些示例代码,让您了解我的意思:

编辑:更新代码

class HomeScreen extends StatefulWidget {
@override
_HomeScreenState createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
bool touchIsInside = true;
GlobalKey touchKey = new GlobalKey();
@override
Widget build(BuildContext context) {
return Center(
child: GestureDetector(
key: touchKey,
onTap: () {
print("Handle regular tap.");
},
onPanUpdate: (DragUpdateDetails details) {
if (touchKey.currentContext == null ||
touchKey.currentContext?.size == null) return;
if (touchKey.currentContext!.size!.width < details.localPosition.dx ||
details.localPosition.dx < 0 ||
touchKey.currentContext!.size!.height <
details.localPosition.dy ||
details.localPosition.dy < 0) {
touchIsInside = false;
} else {
touchIsInside = true;
}
},
onPanEnd: (DragEndDetails details) {
if (touchIsInside) {
print("Handle press ended inside.");
} else {
print("Handle press ended outside.");
}
touchIsInside = true;
},
child: Container(
child: Padding(
padding: EdgeInsets.all(30.0),
child: Text(
"Press me!",
style: TextStyle(color: Colors.white),
),
),
color: Colors.blue),
),
);
}
}

你可以在这里查看它的演示:https://screenrec.com/share/sWHt2zk5SV

您可以使用MouseRegion小部件来跟踪指针是否已进入/退出容器:

https://api.flutter.dev/flutter/widgets/MouseRegion-class.html

在onEnter中,您可以设置一个变量来指示指针在区域内,并在onExit中将其设置为false。

最新更新