检测指针的位置是否在 Widget 内部 onPointerUp 事件

Detecting if the position of pointer is inside the Widget or not onPointerUp event

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

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,
  ),
)

您可以使用 MouseRegion 小部件来跟踪指针是否具有 entered/exited 容器:

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

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

您可以使用 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