Flutter技术问询:如何在鼠标移出PopupMenuItem时关闭自定义showMenu弹窗
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
contextused inNavigator.of(context)has access to the same Navigator that pushed theshowMenuroute. In your current code, thecontextpassed toshowMenuwill work perfectly here, since theMouseRegionis a child of thePopupMenuItemwithin 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 ownMouseRegion(with the samepoplogic), or restructure the menu to wrap all items in a singleMouseRegionfor broader exit detection.
内容的提问来源于stack exchange,提问作者doordarshan bandara
相关产品推荐
相关产品推荐

