MenuBar class
A menu bar that manages cascading child menus.
This is a Material Design menu bar that typically resides above the main body of an application (but can go anywhere) that defines a menu system for invoking callbacks in response to user selection of a menu item.
The menus can be opened with a click or tap. Once a menu is opened, it can be navigated by using the arrow and tab keys or via mouse hover. Selecting a menu item can be done by pressing enter, or by clicking or tapping on the menu item. Clicking or tapping on any part of the user interface that isn't part of the menu system controlled by the same controller will cause all of the menus controlled by that controller to close, as will pressing the escape key.
When a menu item with a submenu is clicked on, it toggles the visibility of the submenu. When the menu item is hovered over, the submenu will open, and hovering over other items will close the previous menu and open the newly hovered one. When those open/close transitions occur, SubmenuButton.onOpen, and SubmenuButton.onClose are called on the corresponding SubmenuButton child of the menu bar.
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)),
),
);
}
}
This example shows a MenuBar that handles keyboard accelerators using MenuAcceleratorLabel. To use the accelerators, press the Alt key to see which letters are underlined in the menu bar, and then press the appropriate letter. Accelerators are not supported on macOS or iOS since those platforms don't support them natively, so this demo will only show a regular Material menu bar on those platforms.
{@macro material_ui.dartpad_guide}
import 'package:flutter/services.dart';
import 'package:material_ui/material_ui.dart';
/// Flutter code sample for [MenuAcceleratorLabel].
void main() => runApp(const MenuAcceleratorApp());
class MyMenuBar extends StatelessWidget {
const MyMenuBar({super.key});
@override
Widget build(BuildContext context) {
return Column(
children: <Widget>[
Row(
mainAxisSize: .min,
children: <Widget>[
Expanded(
child: MenuBar(
children: <Widget>[
SubmenuButton(
menuChildren: <Widget>[
MenuItemButton(
onPressed: () {
showAboutDialog(
context: context,
applicationName: 'MenuBar Sample',
applicationVersion: '1.0.0',
);
},
child: const MenuAcceleratorLabel('&About'),
),
MenuItemButton(
onPressed: () {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Saved!')),
);
},
child: const MenuAcceleratorLabel('&Save'),
),
MenuItemButton(
onPressed: () {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Quit!')),
);
},
child: const MenuAcceleratorLabel('&Quit'),
),
],
child: const MenuAcceleratorLabel('&File'),
),
SubmenuButton(
menuChildren: <Widget>[
MenuItemButton(
onPressed: () {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Magnify!')),
);
},
child: const MenuAcceleratorLabel('&Magnify'),
),
MenuItemButton(
onPressed: () {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Minify!')),
);
},
child: const MenuAcceleratorLabel('Mi&nify'),
),
],
child: const MenuAcceleratorLabel('&View'),
),
],
),
),
],
),
Expanded(
child: FlutterLogo(
size: MediaQuery.of(context).size.shortestSide * 0.5,
),
),
],
);
}
}
class MenuAcceleratorApp extends StatelessWidget {
const MenuAcceleratorApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Shortcuts(
shortcuts: <ShortcutActivator, Intent>{
const SingleActivator(
LogicalKeyboardKey.keyT,
control: true,
): VoidCallbackIntent(() {
debugDumpApp();
}),
},
child: const Scaffold(body: SafeArea(child: MyMenuBar())),
),
);
}
}
See also:
- MenuAnchor, a widget that creates a region with a submenu and shows it when requested.
- SubmenuButton, a menu item which manages a submenu.
- MenuItemButton, a leaf menu item which displays the label, an optional shortcut label, and optional leading and trailing icons.
- 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
Constructors
Properties
-
children
→ List<
Widget> -
The list of menu items that are the top level children of the MenuBar.
final
- clipBehavior → Clip
-
The content will be clipped (or not) according to this option.
final
- controller → MenuController?
-
The MenuController to use for this menu bar.
final
- hashCode → int
-
The hash code for this object.
no setterinherited
- key → Key?
-
Controls how one widget replaces another widget in the tree.
finalinherited
- runtimeType → Type
-
A representation of the runtime type of the object.
no setterinherited
- style → MenuStyle?
-
The MenuStyle that defines the visual attributes of the menu bar.
final
Methods
-
build(
BuildContext context) → Widget -
Describes the part of the user interface represented by this widget.
override
-
createElement(
) → StatelessElement -
Creates a StatelessElement to manage this widget's location in the tree.
inherited
-
debugDescribeChildren(
) → List< DiagnosticsNode> -
Returns a list of DiagnosticsNode objects describing this node's
children.
override
-
debugFillProperties(
DiagnosticPropertiesBuilder properties) → void -
Add additional properties associated with the node.
override
-
noSuchMethod(
Invocation invocation) → dynamic -
Invoked when a nonexistent method or property is accessed.
inherited
-
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