Flutter Popup Menu Button Example

As a part of flutter tutorial series, We’re going to learn, how to implement popup menu button in flutter (PopupMenuButton) with 2 examples.

Usage:

  • These Types of buttons mostly used for showing drop down menu in AppBar
  • Based on user selection you can do some action or navigate between pages.

Flutter Popup Menu Button Example 1

This example, we’re going to use Popup Menu button as page navigation. when user select any option, we’re taking value as route & navigate them to respective pages.

popup-menu-button-example-1
popup-menu-button-example-1

Source code:

class _HomePageState extends State<HomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Popup Menu"),
        actions: [
          PopupMenuButton(
            itemBuilder: (BuildContext bc) => [
              PopupMenuItem(child: Text("New Chat"), value: "/newchat"),
              PopupMenuItem(
                  child: Text("New Group Chat"), value: "/new-group-chat"),
              PopupMenuItem(child: Text("Settings"), value: "/settings"),
            ],
            onSelected: (route) {
              print(route);
              // Note You must create respective pages for navigation
              Navigator.pushNamed(context, route);
            },
          ),
        ],
      ),
      body: Container(),
    );
  }
}

Flutter PopupMenuButton Example 2

This example, we’re going to dynamically add options to menu button using List. When user select any options, we’re going to display it on another Text Widget

popup-menu-button-example-2
popup-menu-button-example-2

Source code

class _HomePageState extends State<HomePage> {
  String _selectedItem = 'Sun';
  List _options = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Popup Menu"),
        actions: [
          PopupMenuButton(
            itemBuilder: (BuildContext bc) {
              return _options
                  .map((day) => PopupMenuItem(
                        child: Text(day),
                        value: day,
                      ))
                  .toList();
            },
            onSelected: (value) {
              setState(() {
                _selectedItem = value;
              });
            },
          ),
        ],
      ),
      body: Center(
        child: Text("Selected Day: $_selectedItem"),
      ),
    );
  }
}

Resources: