showButtonMenu method
A method to show a popup menu with the items supplied to
ContextMenuButton.itemBuilder
at the position of your ContextMenuButton.
By default, it is called when the user taps the button and ContextMenuButton.enabled
is set to true
. Moreover, you can open the button by calling the method manually.
You would access your ContextMenuButtonState using a GlobalKey and
show the menu of the button with globalKey.currentState.showButtonMenu
.
Implementation
void showButtonMenu(Offset triggerPosition) {
final RenderBox button = context.findRenderObject() as RenderBox;
final RenderBox overlay =
Overlay.of(context)!.context.findRenderObject() as RenderBox;
final Rect targetRegion = Rect.fromPoints(
button.localToGlobal(widget.offset, ancestor: overlay),
button.localToGlobal(button.size.bottomRight(Offset.zero),
ancestor: overlay),
);
// Only show the menu if there is something to show
final menu = widget.menu;
if (menu is RawContextMenu && menu.actions(context).isNotEmpty) {
return null;
}
showContextMenu<T>(
context: context,
menu: widget.menu,
targetRegion: targetRegion,
triggerPosition: triggerPosition,
originAligment: widget.originAligment,
aligment: widget.aligment,
).then<void>((T? newValue) {
if (!mounted) return null;
});
}