flutterflutter-stacked

How can I detect cursor hover location on 2 stacked up widgets in Flutter


Currently, I am trying to work on a project that requires me to pass cursor hover behavior from the top stacked widget to its lower widget. While also performing operations needed on that widget itself. This is my current attempt on it:

        Stack(
          children: [
            Center(
              child: MouseRegion(
                onHover: (event) {
                  debugPrint('Red: ${event.position}');
                },
                child: Container(
                  height: 300,
                  width: 300,
                  color: Colors.red,
                ),
              ),
            ),
            Center(
              child: MouseRegion(
                hitTestBehavior: HitTestBehavior.translucent,
                onHover: (event) {
                  debugPrint('Green: ${event.position}');
                },
                child: Container(
                  height: 200,
                  width: 200,
                  color: Colors.green,
                ),
              ),
            ),
          ],
        )

Here, on hovering over the green container, the debugPrint statement of red container, does not get invoked.


Solution

  • It turned out it is quite easy for the MouseRegion widget specifically. We can simply set the opaque property to false, like this:

    Stack(
        children: [
        Center(
            child: MouseRegion(
            onHover: (event) {
                debugPrint('Red: ${event.position}');
            },
            child: Container(
                height: 300,
                width: 300,
                color: Colors.red,
            ),
            ),
        ),
        Center(
            child: MouseRegion(
            opaque: false, //This will let all the mouse events also passed on.
            onHover: (event) {
                debugPrint('Green: ${event.position}');
            },
            child: Container(
                height: 200,
                width: 200,
                color: Colors.green,
            ),
            ),
        ),
        ],
    )