Popup Menu Button in Flutter

Hello Friend, It's time to learn how to create Popup Menu Button in Flutter. It's effortless to crack. Let's start with the code.

I'm using Android Studio, you can also use VS Code or any other editor. Before start, we should discuss the use of the Popup Menu Button.



Use of Popup Menu Button

Basically Popup Menu Button employing an alternate route to go to a screen to another screen. Here these types of alternatives where we will design our application.

Mostly applications using these options.

  • Home
  • Setting
  • Bookmarks
  • Help
  • About
  • Help

We are able to alter as our require.

How to make Custom Popup Menu

Now I begin step by step How to make Custom Popup Menu in Flutter. I will make a class CustomPopupMenu and calling a function on chosen Popup Menu Alternatives.

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

Properties of Popup Menu Button in Flutter

Every widget has a special property, just like that Popup Menu has also Properties, by using we can make our application better.

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

So now continue to developing Popup Menu Button in Flutter. Below, there is a code of a class creating a constructor for requiring title and icon for showing options.

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;
}

Now we will create a list for the collocation of options name and icon. This code will be written in the main class. See example.

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

I'm share a link of view all source code of Popup Menu Button Flutter Application. You can see and use for your application.

Given the above code is for Popup menu button, in this code, we create a function for select any option, let's discuss that.

void _select(CustomPopupMenu choice) {
setState(() {
_selectedChoices = choice;
});
}
Previous
Next Post »