📜  flutter popupmenubutton - Dart (1)

📅  最后修改于: 2023-12-03 15:15:07.579000             🧑  作者: Mango

Flutter PopupMenuButton

PopupMenuButton is a Flutter widget that presents a menu when pressed. It is used to provide additional options to the user. The menu can be created based on a list of options.

Usage

To use PopupMenuButton, first, import the material library:

import 'package:flutter/material.dart';

Then, create a PopupMenuButton widget passing the following parameters:

  • itemBuilder: a function that returns the menu options.
  • onSelected: a function that is called when an item is selected from the menu.

Here's an example:

PopupMenuButton(
  itemBuilder: (BuildContext context) => [
    PopupMenuItem(
      value: 'value1',
      child: Text('Option 1'),
    ),
    PopupMenuItem(
      value: 'value2',
      child: Text('Option 2'),
    ),
    PopupMenuItem(
      value: 'value3',
      child: Text('Option 3'),
    ),
  ],
  onSelected: (value) {
    print('selected value: $value');
  },
)
Customization

PopupMenuButton can be customized by passing the following parameters:

  • child: a widget that is used as the button that triggers the popup menu.
  • tooltip: a string that is displayed when the button is long-pressed.
  • icon: an icon that is displayed on the button.
  • offset: a relative offset from the button where the menu should appear.
  • enabled: a boolean that determines if the button is enabled or disabled.
  • elevation: determines the elevation of the PopupMenuButton.
  • shape: determines the shape of the PopupMenuButton.
  • color: determines the color of the PopupMenuButton.

Here's an example of a customized PopupMenuButton:

PopupMenuButton(
  child: Icon(Icons.more_vert),
  tooltip: 'Options',
  icon: Icon(Icons.settings),
  offset: Offset(0, 50),
  enabled: true,
  elevation: 10,
  shape: RoundedRectangleBorder(
    borderRadius: BorderRadius.circular(10),
  ),
  color: Colors.white,
  itemBuilder: (BuildContext context) => [
    PopupMenuItem(
      value: 'value1',
      child: Text('Option 1'),
    ),
    PopupMenuItem(
      value: 'value2',
      child: Text('Option 2'),
    ),
    PopupMenuItem(
      value: 'value3',
      child: Text('Option 3'),
    ),
  ],
  onSelected: (value) {
    print('selected value: $value');
  },
)

##Conclusion

PopupMenuButton is an essential widget in Flutter that helps to provide additional options to the user. By customizing it, developers can make it look and act exactly as they want.