Flutter Popup Menu Button Example

2
58721
flutter popup menu button tutorial
Flutter popupmenubutton tutorial

This time we are going to create a Flutter Popup Menu Button Example. It’s not simple but custom popupmenubutton in flutter. It is a popup menu with a text and an image. Almost all the medium-scale applications have this feature. Popup menu button makes your app clean and creates a great user experience. 

Example Flutter Popup Menu Button
flutter popupmenu button example image

This is the main skull of PopupMenuButton. As you can see it is custom PopupMenuButton with class CustomPopupMenu. We will create that class and also onSelected we are calling to a function. We are going to code everything in a second. 

Flutter PopupMenuButton Widget

PopupMenuButton(
            elevation: 3.2,
            initialValue: choices[1],
            onCanceled: () {
              print('You have not chossed anything');
            },
            tooltip: 'This is tooltip',
            onSelected: _select,
            itemBuilder: (BuildContext context) {
              return choices.map((CustomPopupMenu choice) {
                return PopupMenuItem(
                  value: choice,
                  child: Text(choice.title),
                );
              }).toList();
            },
          )

Flutter Popup Menu Button Properties 

This widget has a list of properties but I will explain what we have in our example code.

  • elevation: Elevation is used to give shadow below the menu.
  • initialValue: This property highlights a value by default. In our case Bookmarks is highlighted. 
  • onCanceled: This function will be called if you don’t select any value from the popup menu button.
  • tooltip: If you long press the three dots you will able to see a message.
  • itemBuilder: Building a list of items and them making converting to a list.

Let’s keep developing flutter popup menu button example. As you can first of all we need a list and its a custom list with a text and an image. So I will create a class that will hold both these properties. A separate class can help you to make changes as you would like.

So its a CustomPopupMenu class with an icon and string.

import 'package:flutter/material.dart';

class CustomPopupMenu {
  CustomPopupMenu({this.title, this.icon});

  String title;
  IconData icon;
}

Nothing fancy. Just a class with a String and IconData.

Now we have to build a list with all the option we want to show. You have freedom to build this list in CustomPopupMenu class or in the main class. I will write the list code in the main class.

List choices = [
  CustomPopupMenu(title: 'Home', icon: Icons.home),
  CustomPopupMenu(title: 'Bookmarks', icon: Icons.bookmark),
  CustomPopupMenu(title: 'Settings', icon: Icons.settings),
];

To show a image and a text in the middle of the screen. We will create a stateless widget class. The reason to create a Stateless widget class is we are not performing any action on text and image. So it is safe to make it Stateless. Here the code.

class SelectedOption extends StatelessWidget {
  CustomPopupMenu choice;

  SelectedOption({Key key, this.choice}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(choice.icon, size: 140.0, color: Colors.white),
            Text(
              choice.title,
              style: TextStyle(color: Colors.white, fontSize: 30),
            )
          ],
        ),
      ),
    );
  }
}

Just putting an object in centre of the screen. Note: CustomPopupMenu object is passed to the constructor and inilitized. 

So for now you have a better understanding about the code. To make it more clear let’s join all the pieces together.

import 'package:first_app/CustomPopupMenu.dart';
import 'package:flutter/material.dart';

void main() =>
    runApp(MaterialApp(title: "Popup Menu Button", home: MainActivity()));

class MainActivity extends StatefulWidget {
  @override
  _MainActivityState createState() => _MainActivityState();
}

List choices = [
  CustomPopupMenu(title: 'Home', icon: Icons.home),
  CustomPopupMenu(title: 'Bookmarks', icon: Icons.bookmark),
  CustomPopupMenu(title: 'Settings', icon: Icons.settings),
];

class _MainActivityState extends State {
  CustomPopupMenu _selectedChoices = choices[0];

  void _select(CustomPopupMenu choice) {
    setState(() {
      _selectedChoices = choice;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.yellow,
      appBar: AppBar(
        title: Text('Popup Menu Button'),
        actions: [
          PopupMenuButton(
            elevation: 3.2,
            initialValue: choices[1],
            onCanceled: () {
              print('You have not chossed anything');
            },
            tooltip: 'This is tooltip',
            onSelected: _select,
            itemBuilder: (BuildContext context) {
              return choices.map((CustomPopupMenu choice) {
                return PopupMenuItem(
                  value: choice,
                  child: Text(choice.title),
                );
              }).toList();
            },
          )
        ],
      ),
      body: bodyWidget(),
    );
  }

  bodyWidget() {
    return Container(
      child: SelectedOption(choice: _selectedChoices),
    );
  }
}

class SelectedOption extends StatelessWidget {
  CustomPopupMenu choice;

  SelectedOption({Key key, this.choice}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(choice.icon, size: 140.0, color: Colors.white),
            Text(
              choice.title,
              style: TextStyle(color: Colors.white, fontSize: 30),
            )
          ],
        ),
      ),
    );
  }
}

I have explained everything except the _select function. It easy, on onSelected this function will be called and update the CustomPopupMenu object with a new selected object’s value. 

void _select(CustomPopupMenu choice) {
    setState(() {
      _selectedChoices = choice;
    });
  }

I hope this tutorial has helped you and I was able perform a Flutter PopUp Menu Button Example. You can read more about flutter at popupmenubutton official documentation. Don’t forget to learn about how to create 

2 COMMENTS

    • CustomPopupMenu.dart is class and first_app is the package that contains the class. Just creat CustomPopupMenu.dart class in any package and import. It will work fine.

LEAVE A REPLY

Please enter your comment!
Please enter your name here