Popup Menu Button in Flutter
Introduction
The PopupMenuButton widget in Flutter is used to display a menu when pressed and allows you to select from a list of options. It’s commonly used for overflow menus, showing choices related to an item.
Example 1: Basic Popup Menu Button
In this example below, you will learn to create a basic popup menu button with a list of items. When you press the button, a menu will appear with the available options.
PopupMenuButton<int>(
onSelected: (int result) {
setState(() {
_selectedMenu = result;
});
},
itemBuilder: (BuildContext context) => <PopupMenuEntry<int>>[
const PopupMenuItem<int>(
value: 1,
child: Text('About Us'),
),
const PopupMenuItem<int>(
value: 2,
child: Text('Contact Us'),
),
const PopupMenuItem<int>(
value: 3,
child: Text('Privacy Policy'),
),
],
)
Example 2: Popup Menu Button with Icons
In this example below, you will learn to create a popup menu button with icons for the menu items. When you press the button, a menu will appear with the available options, each with an icon.
PopupMenuButton<int>(
onSelected: (int result) {
setState(() {
_selectedMenu = result;
});
},
itemBuilder: (BuildContext context) => <PopupMenuEntry<int>>[
const PopupMenuItem<int>(
value: 1,
child: ListTile(
leading: Icon(Icons.info),
title: Text('About Us'),
),
),
const PopupMenuItem<int>(
value: 2,
child: ListTile(
leading: Icon(Icons.phone),
title: Text('Contact Us'),
),
),
const PopupMenuItem<int>(
value: 3,
child: ListTile(
leading: Icon(Icons.privacy_tip),
title: Text('Privacy Policy'),
),
),
],
)
Challenge
Create a popup menu button that shows options for changing the theme of the app (Light, Dark, System Default).