Widgets 14 | PopupMenuButton

In this tutorial, you will learn how to use the PopupMenuButton in the flutter.

Before Start

Before starting our tutorial, we should create a page to contain our code.

import "package:flutter/material.dart";
import 'package:flutter_widgets/const/_const.dart';

class PopupMenuButtonPage extends StatefulWidget {
  @override
  _PopupMenuButtonState createState() => _PopupMenuButtonState();
}

class _PopupMenuButtonState extends State<PopupMenuButtonPage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(PageName.POPUP_MENU_BUTTON),
      ),
      body: SingleChildScrollView(
        child: Column(
          children: <Widget>[
            //our code.
            SizedBox(height: 600)
          ],
        ),
      ),
    );
  }
}

This is an empty page with a title.

Simple Use

The PopupMenuButton is similar with the DropdownButton, but has a bit different with it. The PopupMenuButton shows the menu but do not change the current button,you can do more things than the DropdownButton. So let's look at an example.

Widget _simplePopup() => PopupMenuButton<int>(
          itemBuilder: (context) => [
                PopupMenuItem(
                  value: 1,
                  child: Text("First"),
                ),
                PopupMenuItem(
                  value: 2,
                  child: Text("Second"),
                ),
              ],
        );

It will show three points in the picture. When you click it, it will show you a menu to choose.

Constructor

Let's look at its constructor for more use.

PopupMenuButton({
    Key key,
    @required this.itemBuilder,
    this.initialValue,
    this.onSelected,
    this.onCanceled,
    this.tooltip,
    this.elevation = 8.0,
    this.padding = const EdgeInsets.all(8.0),
    this.child,
    this.icon,
    this.offset = Offset.zero,
  }) 

The constructor has some parameters we have used them before, but some are not, so let's use them one by one.

itemBuilder

This parameter defines as the blow.

  final PopupMenuItemBuilder<T> itemBuilder;

If you just look at this, you may do not know how to use it. You should look at the detail of the builder.

typedef PopupMenuItemBuilder<T> = List<PopupMenuEntry<T>> Function(BuildContext context);

It is a function and should return list with a type of the PopupMenuEntry. It is an abstract class, so we should use its subclasses. The relationship of the extends is below.

So we can add the three classes to the list.So let's use them at the same time.

  Widget _threeItemPopup() => PopupMenuButton(
          itemBuilder: (context) {
            var list = List<PopupMenuEntry<Object>>();
            list.add(
              PopupMenuItem(
                child: Text("Setting Language"),
                value: 1,
              ),
            );
            list.add(
              PopupMenuDivider(
                height: 10,
              ),
            );
            list.add(
              CheckedPopupMenuItem(
                child: Text(
                  "English",
                  style: TextStyle(color: TEXT_BLACK),
                ),
                value: 2,
                checked: true,
              ),
            );
            return list;
          },
          icon: Icon(
            Icons.settings,
            size: 50,
            color: Colors.white,
          ),
        );

It will show as follows. When you click the button with a setting icon, it will show the right part, the upper item is the PopupMenuItem, the middle line the PopupMenuDivider, the bottom one is the CheckedPopupMenuItem.

onSelected

In this part, I will give you an example as below.

  Widget _selectPopup() => PopupMenuButton<int>(
          itemBuilder: (context) => [
                PopupMenuItem(
                  value: 1,
                  child: Text("First"),
                ),
                PopupMenuItem(
                  value: 2,
                  child: Text("Second"),
                ),
              ],
          initialValue: 2,
          onCanceled: () {
            print("You have canceled the menu.");
          },
          onSelected: (value) {
            print("value:$value");
          },
          icon: Icon(Icons.list),
        );

The initialValue will highlight the item with a grey background when showing the menu. The onCanceled is the function that will be called when you click the area that out of the menu.The onSelected is also a function with a value parameter that is the same as the value of the PopupMenuItem. The icon shows our button for us to click. The result is below.

When you click the item of the menu or other areas that outside of the menu. It will print in the console like this.

I/flutter ( 5472): value:1
I/flutter ( 5472): You have canceled the menu.

padding

This is very similar to us, so I just give an example to show the effect and see which part will change.

   Widget _paddingPopup() => PopupMenuButton<int>(
          itemBuilder: (context) => [
                PopupMenuItem(
                  value: 1,
                  child: Text(
                    "English",
                    style:
                        TextStyle(color: PURPLE, fontWeight: FontWeight.w700),
                  ),
                ),
                PopupMenuItem(
                  value: 2,
                  child: Text(
                    "Chinese",
                    style:
                        TextStyle(color: PURPLE, fontWeight: FontWeight.w700),
                  ),
                ),
              ],
          elevation: 4,
          padding: EdgeInsets.symmetric(horizontal: 50),
        );

The elevation controls the shadow of the menu. The padding sets the distance of the button.

child

This parameter will draw a widget for the button, but you should know, you can only choose either child or icon, do not use both of them.

  Widget _childPopup() => PopupMenuButton<int>(
          itemBuilder: (context) => [
                PopupMenuItem(
                  value: 1,
                  child: Text(
                    "Earth",
                    style: TextStyle(
                        color: TEXT_BLACK, fontWeight: FontWeight.w700),
                  ),
                ),
                PopupMenuItem(
                  value: 2,
                  child: Text(
                    "Moon",
                    style: TextStyle(
                        color: TEXT_BLACK, fontWeight: FontWeight.w700),
                  ),
                ),
                PopupMenuItem(
                  value: 3,
                  child: Text(
                    "Sun",
                    style: TextStyle(
                        color: TEXT_BLACK, fontWeight: FontWeight.w700),
                  ),
                ),
              ],
          child: Container(
            height: 50,
            width: 200,
            decoration: ShapeDecoration(
              color: GREEN,
              shape: StadiumBorder(
                side: BorderSide(color: TEXT_BLACK, width: 2),
              ),
            ),
            child: Icon(Icons.airplanemode_active),
          ),
        );

It will show as follows. The button will show our custom shape.

offset

This can control the location of the menu. So you should set this parameter to show your menu in the fit position. Let's see if we just set it to the Offset(0,100), which position it will be.

Widget _offsetPopup() => PopupMenuButton<int>(
          itemBuilder: (context) => [
                PopupMenuItem(
                  value: 1,
                  child: Text(
                    "Flutter Open",
                    style: TextStyle(
                        color: TEXT_BLACK, fontWeight: FontWeight.w700),
                  ),
                ),
                PopupMenuItem(
                  value: 2,
                  child: Text(
                    "Flutter Tutorial",
                    style: TextStyle(
                        color: TEXT_BLACK, fontWeight: FontWeight.w700),
                  ),
                ),
              ],
          icon: Icon(Icons.library_add),
          offset: Offset(0, 100),
        );

It will show like this.

If you don't set the offset, it will use the default value Offset.zero.It will show as below.

Conclusion

In this tutorial, we have learned many parameters of the PopupMenuButton. A bit difficult one is the itemBuilder, it isn't very obvious to a newer, it is a function that return list. The others will be easy to understand.

Thanks for your reading!

The end.

Whole code in GitHub,star to support.

Facebook Page

Twitter

GitHub

Medium

Last updated