Flutter PopupMenuButton

aadarshk7

Aadarsh Kunwar

Posted on September 9, 2024

Flutter PopupMenuButton

In Flutter, PopupMenuButton is a widget that provides a menu for selecting among a set of options. When tapped, it displays a list of items in a pop-up that the user can choose from.

Here’s a basic example of how to use PopupMenuButton:

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: PopupMenuExample(),
    );
  }
}

class PopupMenuExample extends StatefulWidget {
  @override
  _PopupMenuExampleState createState() => _PopupMenuExampleState();
}

class _PopupMenuExampleState extends State<PopupMenuExample> {
  String _selectedOption = 'None';

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Popup Menu Button Example'),
        actions: [
          PopupMenuButton<String>(
            onSelected: (String result) {
              setState(() {
                _selectedOption = result;
              });
            },
            itemBuilder: (BuildContext context) => <PopupMenuEntry<String>>[
              const PopupMenuItem<String>(
                value: 'Option 1',
                child: Text('Option 1'),
              ),
              const PopupMenuItem<String>(
                value: 'Option 2',
                child: Text('Option 2'),
              ),
              const PopupMenuItem<String>(
                value: 'Option 3',
                child: Text('Option 3'),
              ),
            ],
          ),
        ],
      ),
      body: Center(
        child: Text('Selected option: $_selectedOption'),
      ),
    );
  }
}

Enter fullscreen mode Exit fullscreen mode

Explanation:

  • PopupMenuButton: Creates a button that shows a pop-up menu.
  • onSelected: Callback that is invoked when an item from the menu is selected.
  • PopupMenuItem: Each item in the pop-up menu with a value and child (usually a Text widget).
💖 💪 🙅 🚩
aadarshk7
Aadarsh Kunwar

Posted on September 9, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Flutter PopupMenuButton
flutter Flutter PopupMenuButton

September 9, 2024

Flutter Circular Progress Bar
flutter Flutter Circular Progress Bar

August 27, 2024