flutter

How to know the mouse left the Widget from which side in flutter?


I know that MouseRegion.onExit can be used to detect when a mouse leaves a Widget, but I need to know whether the mouse is leaving from the left, right, top or bottom edge of a Widget. Is there a simple way to do this in flutter?


Solution

  • onExit callback is providing the details of the mouse pointer which has a property called localPosition. from localPosition we can get the x and y position of the mouse pointer. and then you can check it if details.localPosition.dx <= 0 it means the mouse exits on the left side. and same for the dy if details.localPosition.dy <= 0 it means the mouse exits on the top side.

    checkout this gist or try it on DatPad in which I implemented this logic and created a simple animation in which the shadow move on the opposite side of mouse exit.

    Check the results: Here's a simple Flutter widget that animates its shadow position based on the direction the mouse pointer exits the widget