Flutter: PopupMenuButton Usage and Menu Structures
personAhmet Balaman
calendar_today
FlutterPopupMenuMenuWidgetUINavigation
PopupMenuButton is a menu structure that provides convenience to users and becomes visible as a result of an action. Menus consist of items, and each item must have a value. Otherwise, we cannot capture the click event.
Live Demo
You can try this widget in the interactive example below:
💡 If the example above doesn't load, click DartPad to run it in a new tab.
Basic Usage
PopupMenuButton<String>(
onSelected: (String value) {
print('Selected: $value');
},
itemBuilder: (BuildContext context) => [
PopupMenuItem<String>(
value: 'edit',
child: Text('Edit'),
),
PopupMenuItem<String>(
value: 'delete',
child: Text('Delete'),
),
],
)Using with Enum
Using enum is recommended for type safety:
enum MenuAction { edit, delete, share }
PopupMenuButton<MenuAction>(
onSelected: (MenuAction action) {
switch (action) {
case MenuAction.edit:
// Edit operation
break;
case MenuAction.delete:
// Delete operation
break;
case MenuAction.share:
// Share operation
break;
}
},
itemBuilder: (context) => [
PopupMenuItem(value: MenuAction.edit, child: Text('Edit')),
PopupMenuItem(value: MenuAction.delete, child: Text('Delete')),
PopupMenuItem(value: MenuAction.share, child: Text('Share')),
],
)Menu Items with Icons
PopupMenuItem<String>(
value: 'settings',
child: Row(
children: [
Icon(Icons.settings),
SizedBox(width: 10),
Text('Settings'),
],
),
)PopupMenuDivider
To add a separator between menu items:
itemBuilder: (context) => [
PopupMenuItem(value: 'edit', child: Text('Edit')),
PopupMenuItem(value: 'copy', child: Text('Copy')),
PopupMenuDivider(), // Separator line
PopupMenuItem(value: 'delete', child: Text('Delete')),
]Important Properties
| Property | Description |
|---|---|
onSelected |
Called when item is selected |
itemBuilder |
Creates menu items |
icon |
Menu button icon |
child |
Custom button widget |
offset |
Menu position offset |
shape |
Menu shape |
color |
Menu background color |
enabled |
Menu active/inactive state |
Using with Custom Button
PopupMenuButton<String>(
child: Container(
padding: EdgeInsets.all(12),
decoration: BoxDecoration(
color: Colors.blue,
borderRadius: BorderRadius.circular(8),
),
child: Row(
children: [
Text('Menu', style: TextStyle(color: Colors.white)),
Icon(Icons.arrow_drop_down, color: Colors.white),
],
),
),
itemBuilder: (context) => [...],
)Summary
- PopupMenuButton: Creates dropdown menu
- PopupMenuItem: Represents menu items
- value: Unique value for each item (required)
- onSelected: Triggered when selection is made
- PopupMenuDivider: Separator between items
PopupMenuButton is ideal for presenting contextual options to users.