skip to Main Content

In flutter, to change a mouse cursor we must use the MouseRegion and a setState:

MouseRegion(cursor: _cursor);

setState(() {
    _cursor = SystemMouseCursors.grab;
});

But, the setState is rebuilding the widgets. It sounds crazy to rebuild all the widgets for changing the cursor (which is not related to my user interface, it is the system mouse cursor). In my current application, changing the cursor at each mouse movement trigger a rebuild, and so it is visually flashing ! For example I have a table that reload its data !

I have search for another way to handle this. I tried with MouseTracker but we have no more access to the MouseAnnotation : https://docs.flutter.dev/release/breaking-changes/mouse-tracker-no-longer-attaches-annotations

So, I have no idea how to track and change the mouse cursor with a rebuild. And you ?

2

Answers


  1. Chosen as BEST ANSWER

    I use a Stack and I use the property MouseRegion.opaque that way. I use the stack to put the mouse region at the top z-order, and so when it rebuilt, nothing else is rebuilt:

    return Stack(
          children: [
            _buildContent(),
            ValueListenableBuilder(
                valueListenable: _mouseCursor,
                builder: (context, value, child) {
                  return MouseRegion(
                    opaque: false,
                    cursor: value,
                    onHover: _onMouseMove,
                  );
                }),
          ],
        );
    

    Where

    _mouseCursor is a ValueNotifier<MouseCursor> to trigger refreshs.


  2. You don’t need the setState at all, remove it.

    to make the cursor change when hovering above a certain widget, just warp it with the MouseRegion and change the cursor, that’s it.

    an example:

    Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: MouseRegion(
          cursor: SystemMouseCursors.grab, // Change cursor when hovering
          child: Container(
            width: 200,
            height: 200,
            color: Colors.blue,
            child: const Center(
              child: Text(
                'Hover over me!',
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 24,
                ),
              ),
            ),
          ),
        ),
      ),
    );
    

    }

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search