23.3 C
New York
Wednesday, August 17, 2022

Flutter: PopupMenuButton example

- Advertisement -

An example of the PopupMenuButton widget in Flutter.

By default, the PopupMenuButton widget creates a three-dot icon. When the user taps this icon, a menu with one or multiple items will show up. After the user selects an item, the menu will be dismissed.Advertisements

Sample code:

PopupMenuButton(
              onSelected: (selectedValue) {
                print(selectedValue);
              },
              itemBuilder: (BuildContext ctx) => [
                    PopupMenuItem(child: Text('Option 1'), value: '1'),
                    PopupMenuItem(child: Text('Option 2'), value: '2'),
                    PopupMenuItem(child: Text('Option 3'), value: '3'),
                    PopupMenuItem(child: Text('Option 4'), value: '4'),
              ]
)

The Complete Example

Full code in main.dart:

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      // Hide the debug banner
      debugShowCheckedModeBanner: false,
      title: 'Kindacode.com',
      home: HomeScreen(),
    );
  }
}

class HomeScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Kindacode.com'),
        actions: [
          PopupMenuButton(
              onSelected: (selectedValue) {
                print(selectedValue);
              },
              itemBuilder: (BuildContext ctx) => [
                    PopupMenuItem(child: Text('Option 1'), value: '1'),
                    PopupMenuItem(child: Text('Option 2'), value: '2'),
                    PopupMenuItem(child: Text('Option 3'), value: '3'),
                    PopupMenuItem(child: Text('Option 4'), value: '4'),
                  ]
            )
        ],
      ),
      body: Center(),
    );
  }
}

Output:

Conclusion

AdvertisementsWe’ve successfully implemented a simple PopupMenuButton in an app bar. If you’d like to explore more new and interesting stuff in Flutter, take a look at the following articles:

You can also take a tour around our Flutter topic page and Dart topic page to see the latest tutorials and examples.

Advertisements
- Advertisement -

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles