Skip to content

MouseRegion triggers onEnter/onExit while a build is in progress #42370

@emshack

Description

@emshack

My desktop app includes a list of elements, each of which should highlight when the mouse is within their bounds. I'm using MouseRegion to make this happen. My MouseRegion widget looks something like this:

MouseRegion(
    child: elementWidget,
    onEnter: () => setState(() {
        highlighedElements.add(elementData);
    }),
    onExit:  () => setState(() {
        highlighedElements.remove(elementData);
    }),
)

Additionally, elementWidget itself is interactive beyond the hover effect, and it's possible to trigger a rebuild based on that interaction. This creates a problem-- if the mouse is hovering over the MouseRegion when elementWidget rebuilds, MouseRegion calls onExit (and would call onEnter immediately after if successful). Because onExit includes a setState() call, an error is thrown for calling setState during a build.

In my case, it's usually possible to add special-case logic to onEnter and onExit to get around this and only conditionally call the setState, but this has been coming up a lot in my app, and I'm guessing it's pretty common in other apps to include a setState in onEnter/onExit. Might it be possible for onEnter and onExit to not be called when the child widget is rebuilt, to avoid this issue?

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions