MenuItemButton class
A button for use in a MenuBar, in a menu created with MenuAnchor, or on its own, that can be activated by click or keyboard navigation.
This widget represents a leaf entry in a menu hierarchy that is typically part of a MenuBar, but may be used independently, or as part of a menu created with a MenuAnchor.
Menus using MenuItemButton can have a SingleActivator or CharacterActivator assigned to them as their MenuItemButton.shortcut, which will display an appropriate shortcut hint. Even though the shortcut labels are displayed in the menu, shortcuts are not automatically handled. They must be available in whatever context they are appropriate, and handled via another mechanism.
If shortcuts should be generally enabled, but are not easily defined in a context surrounding the menu bar, consider registering them with a ShortcutRegistry (one is already included in the WidgetsApp, and thus also MaterialApp and CupertinoApp), as shown in the example below. To be sure that selecting a menu item and triggering the shortcut do the same thing, it is recommended that they call the same callback.
This example shows a MenuBar that contains a single top level menu, containing three items: "About", a checkbox menu item for showing a message, and "Quit". The items are identified with an enum value, and the shortcuts are registered globally with the ShortcutRegistry.
{@macro material_ui.dartpad_guide}
import 'package:flutter/services.dart';
import 'package:material_ui/material_ui.dart';
/// Flutter code sample for [MenuBar].
void main() => runApp(const MenuBarApp());
/// A class for consolidating the definition of menu entries.
///
/// This sort of class is not required, but illustrates one way that defining
/// menus could be done.
class MenuEntry {
const MenuEntry({
required this.label,
this.shortcut,
this.onPressed,
this.menuChildren,
}) : assert(
menuChildren == null || onPressed == null,
'onPressed is ignored if menuChildren are provided',
);
final String label;
final MenuSerializableShortcut? shortcut;
final VoidCallback? onPressed;
final List<MenuEntry>? menuChildren;
static List<Widget> build(
List<MenuEntry> selections, [
Duration hoverOpenDelay = .zero,
]) {
Widget buildSelection(MenuEntry selection) {
if (selection.menuChildren != null) {
return SubmenuButton(
menuChildren: MenuEntry.build(
selection.menuChildren!,
const Duration(milliseconds: 150),
),
child: Text(selection.label),
);
}
return MenuItemButton(
shortcut: selection.shortcut,
onPressed: selection.onPressed,
child: Text(selection.label),
);
}
return selections.map<Widget>(buildSelection).toList();
}
static Map<MenuSerializableShortcut, Intent> shortcuts(
List<MenuEntry> selections,
) {
final Map<MenuSerializableShortcut, Intent> result =
<MenuSerializableShortcut, Intent>{};
for (final MenuEntry selection in selections) {
if (selection.menuChildren != null) {
result.addAll(MenuEntry.shortcuts(selection.menuChildren!));
} else {
if (selection.shortcut != null && selection.onPressed != null) {
result[selection.shortcut!] = VoidCallbackIntent(
selection.onPressed!,
);
}
}
}
return result;
}
}
class MyMenuBar extends StatefulWidget {
const MyMenuBar({super.key, required this.message});
final String message;
@override
State<MyMenuBar> createState() => _MyMenuBarState();
}
class _MyMenuBarState extends State<MyMenuBar> {
ShortcutRegistryEntry? _shortcutsEntry;
String? _lastSelection;
Color get backgroundColor => _backgroundColor;
Color _backgroundColor = Colors.red;
set backgroundColor(Color value) {
if (_backgroundColor != value) {
setState(() {
_backgroundColor = value;
});
}
}
bool get showingMessage => _showMessage;
bool _showMessage = false;
set showingMessage(bool value) {
if (_showMessage != value) {
setState(() {
_showMessage = value;
});
}
}
@override
void dispose() {
_shortcutsEntry?.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Column(
children: <Widget>[
Row(
mainAxisSize: .min,
children: <Widget>[
Expanded(child: MenuBar(children: MenuEntry.build(_getMenus()))),
],
),
Expanded(
child: Container(
alignment: .center,
color: backgroundColor,
child: Column(
mainAxisAlignment: .center,
children: <Widget>[
Padding(
padding: const .all(12.0),
child: Text(
showingMessage ? widget.message : '',
style: Theme.of(context).textTheme.headlineSmall,
),
),
Text(
_lastSelection != null
? 'Last Selected: $_lastSelection'
: '',
),
],
),
),
),
],
);
}
List<MenuEntry> _getMenus() {
final List<MenuEntry> result = <MenuEntry>[
MenuEntry(
label: 'Menu Demo',
menuChildren: <MenuEntry>[
MenuEntry(
label: 'About',
onPressed: () {
showAboutDialog(
context: context,
applicationName: 'MenuBar Sample',
applicationVersion: '1.0.0',
);
setState(() {
_lastSelection = 'About';
});
},
),
MenuEntry(
label: showingMessage ? 'Hide Message' : 'Show Message',
onPressed: () {
setState(() {
_lastSelection = showingMessage
? 'Hide Message'
: 'Show Message';
showingMessage = !showingMessage;
});
},
shortcut: const SingleActivator(
LogicalKeyboardKey.keyS,
control: true,
),
),
// Hides the message, but is only enabled if the message isn't
// already hidden.
MenuEntry(
label: 'Reset Message',
onPressed: showingMessage
? () {
setState(() {
_lastSelection = 'Reset Message';
showingMessage = false;
});
}
: null,
shortcut: const SingleActivator(LogicalKeyboardKey.escape),
),
MenuEntry(
label: 'Background Color',
menuChildren: <MenuEntry>[
MenuEntry(
label: 'Red Background',
onPressed: () {
setState(() {
_lastSelection = 'Red Background';
backgroundColor = Colors.red;
});
},
shortcut: const SingleActivator(
LogicalKeyboardKey.keyR,
control: true,
),
),
MenuEntry(
label: 'Green Background',
onPressed: () {
setState(() {
_lastSelection = 'Green Background';
backgroundColor = Colors.green;
});
},
shortcut: const SingleActivator(
LogicalKeyboardKey.keyG,
control: true,
),
),
MenuEntry(
label: 'Blue Background',
onPressed: () {
setState(() {
_lastSelection = 'Blue Background';
backgroundColor = Colors.blue;
});
},
shortcut: const SingleActivator(
LogicalKeyboardKey.keyB,
control: true,
),
),
],
),
],
),
];
// (Re-)register the shortcuts with the ShortcutRegistry so that they are
// available to the entire application, and update them if they've changed.
_shortcutsEntry?.dispose();
_shortcutsEntry = ShortcutRegistry.of(
context,
).addAll(MenuEntry.shortcuts(result));
return result;
}
}
class MenuBarApp extends StatelessWidget {
const MenuBarApp({super.key});
static const String kMessage = '"Talk less. Smile more." - A. Burr';
@override
Widget build(BuildContext context) {
return const MaterialApp(
home: Scaffold(
body: SafeArea(child: MyMenuBar(message: kMessage)),
),
);
}
}
See also:
- MenuBar, a class that creates a top level menu bar in a Material Design style.
- MenuAnchor, a widget that creates a region with a submenu and shows it when requested.
- SubmenuButton, a menu item similar to this one which manages a submenu.
- PlatformMenuBar, which creates a menu bar that is rendered by the host platform instead of by Flutter (on macOS, for example).
- ShortcutRegistry, a registry of shortcuts that apply for the entire application.
- VoidCallbackIntent, to define intents that will call a VoidCallback and work with the Actions and Shortcuts system.
- CallbackShortcuts to define shortcuts that call a callback without involving Actions.
- Inheritance
-
- Object
- DiagnosticableTree
- Widget
- StatefulWidget
- MenuItemButton
Constructors
-
MenuItemButton({Key? key, VoidCallback? onPressed, ValueChanged<
bool> ? onHover, bool requestFocusOnHover = true, ValueChanged<bool> ? onFocusChange, FocusNode? focusNode, bool autofocus = false, MenuSerializableShortcut? shortcut, String? semanticsLabel, ButtonStyle? style, MaterialStatesController? statesController, Clip clipBehavior = Clip.none, Widget? leadingIcon, Widget? trailingIcon, bool closeOnActivate = true, Axis overflowAxis = Axis.horizontal, Widget? child}) -
Creates a const MenuItemButton.
const
Properties
- autofocus → bool
-
True if this widget will be selected as the initial focus when no other
node in its scope is currently focused.
final
- child → Widget?
-
The widget displayed in the center of this button.
final
- clipBehavior → Clip
-
The content will be clipped (or not) according to this option.
final
- closeOnActivate → bool
-
Determines if the menu will be closed when a MenuItemButton
is pressed.
final
- enabled → bool
-
Whether the button is enabled or disabled.
no setter
- focusNode → FocusNode?
-
An optional focus node to use as the focus node for this widget.
final
- hashCode → int
-
The hash code for this object.
no setterinherited
- key → Key?
-
Controls how one widget replaces another widget in the tree.
finalinherited
- leadingIcon → Widget?
-
An optional icon to display before the child label.
final
-
onFocusChange
→ ValueChanged<
bool> ? -
Handler called when the focus changes.
final
-
onHover
→ ValueChanged<
bool> ? -
Called when a pointer enters or exits the button response area.
final
- onPressed → VoidCallback?
-
Called when the button is tapped or otherwise activated.
final
- overflowAxis → Axis
-
The direction in which the menu item expands.
final
- requestFocusOnHover → bool
-
Determine if hovering can request focus.
final
- runtimeType → Type
-
A representation of the runtime type of the object.
no setterinherited
- semanticsLabel → String?
-
An optional Semantics label, applied to the entire MenuItemButton.
final
- shortcut → MenuSerializableShortcut?
-
The optional shortcut that selects this MenuItemButton.
final
- statesController → MaterialStatesController?
-
Represents the interactive "state" of this widget in terms of
a set of WidgetStates, like WidgetState.pressed and
WidgetState.focused.
final
- style → ButtonStyle?
-
Customizes this button's appearance.
final
- trailingIcon → Widget?
-
An optional icon to display after the child label.
final
Methods
-
createElement(
) → StatefulElement -
Creates a StatefulElement to manage this widget's location in the tree.
inherited
-
createState(
) → State< MenuItemButton> -
Creates the mutable state for this widget at a given location in the tree.
override
-
debugDescribeChildren(
) → List< DiagnosticsNode> -
Returns a list of DiagnosticsNode objects describing this node's
children.
inherited
-
debugFillProperties(
DiagnosticPropertiesBuilder properties) → void -
Add additional properties associated with the node.
override
-
defaultStyleOf(
BuildContext context) → ButtonStyle - Defines the button's default appearance.
-
noSuchMethod(
Invocation invocation) → dynamic -
Invoked when a nonexistent method or property is accessed.
inherited
-
themeStyleOf(
BuildContext context) → ButtonStyle? - Returns the MenuButtonThemeData.style of the closest MenuButtonTheme ancestor.
-
toDiagnosticsNode(
{String? name, DiagnosticsTreeStyle? style}) → DiagnosticsNode -
Returns a debug representation of the object that is used by debugging
tools and by DiagnosticsNode.toStringDeep.
inherited
-
toString(
{DiagnosticLevel minLevel = DiagnosticLevel.info}) → String -
A string representation of this object.
inherited
-
toStringDeep(
{String prefixLineOne = '', String? prefixOtherLines, DiagnosticLevel minLevel = DiagnosticLevel.debug, int wrapWidth = 65}) → String -
Returns a string representation of this node and its descendants.
inherited
-
toStringShallow(
{String joiner = ', ', DiagnosticLevel minLevel = DiagnosticLevel.debug}) → String -
Returns a one-line detailed description of the object.
inherited
-
toStringShort(
) → String -
A short, textual description of this widget.
inherited
Operators
-
operator ==(
Object other) → bool -
The equality operator.
inherited
Static Methods
-
styleFrom(
{Color? foregroundColor, Color? backgroundColor, Color? disabledForegroundColor, Color? disabledBackgroundColor, Color? shadowColor, Color? surfaceTintColor, Color? iconColor, double? iconSize, Color? disabledIconColor, TextStyle? textStyle, Color? overlayColor, double? elevation, EdgeInsetsGeometry? padding, Size? minimumSize, Size? fixedSize, Size? maximumSize, MouseCursor? enabledMouseCursor, MouseCursor? disabledMouseCursor, BorderSide? side, OutlinedBorder? shape, VisualDensity? visualDensity, MaterialTapTargetSize? tapTargetSize, Duration? animationDuration, bool? enableFeedback, AlignmentGeometry? alignment, InteractiveInkFeatureFactory? splashFactory}) → ButtonStyle - A static convenience method that constructs a MenuItemButton's ButtonStyle given simple values.