You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter技术问询:如何在鼠标移出PopupMenuItem时关闭自定义showMenu弹窗

Solution: Close showMenu on Mouse Exit from PopupMenuItem

Got it, let's tackle this problem. To close the showMenu popup when the mouse exits your PopupMenuItem, you just need to manually pop the route that showMenu pushes onto the navigation stack. Here's how to adjust your code:

void _showPopupMenu() async { 
  await showMenu(
    constraints: BoxConstraints(minWidth: 800),
    color: Colors.black.withOpacity(0.5),
    context: context,
    position: RelativeRect.fromLTRB(150, 50, 150, 100),
    items: [
      PopupMenuItem(
        enabled: false,
        onTap: null,
        child: MouseRegion(
          onExit: (e) {
            // Close the showMenu popup by popping the route
            Navigator.of(context).pop();
          },
          child: Container(
            width: 800,
            height: 400,
            child: Column(
              children: [
                Row(
                  children: [Text('Hello')],
                )
              ],
            ),
          ),
        ))
    ],
    elevation: 8.0,
  ).then((value) {
    if (value != null) print(value);
  });
}

How it works

The showMenu function pushes a temporary route onto the Flutter navigation stack. Calling Navigator.of(context).pop() removes this route, which immediately closes the popup as soon as the mouse exits the MouseRegion wrapped container.

Key Notes

  • Make sure the context used in Navigator.of(context) has access to the same Navigator that pushed the showMenu route. In your current code, the context passed to showMenu will work perfectly here, since the MouseRegion is a child of the PopupMenuItem within that menu.
  • If you have multiple PopupMenuItems and want to close the menu when the mouse exits any of them, you can wrap each item in its own MouseRegion (with the same pop logic), or restructure the menu to wrap all items in a single MouseRegion for broader exit detection.

内容的提问来源于stack exchange,提问作者doordarshan bandara

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.27 20:52:35