flutterflutter-appbarflutter-showmodalbottomsheet

Flutter Modal Bottom Sheet is not working with a Popup Menu Button inside an AppBar


I've got the problem that the Method "showModalBottomSheet" is not working inside the "onTap" function of a Popup Menu Item. The Modal Bottom Sheet is not showing up when clicking on a Popup Menu Entry.

Here is my Code inside the actions parameter of an AppBar:

actions: [
            PopupMenuButton(
                itemBuilder: (BuildContext context) => choices
                    .map((Choice choice) => PopupMenuItem<Choice>(
                          child: Row(
                            children: [
                              choice.icon,
                              SizedBox(width: 15),
                              Text(choice.text),
                            ],
                          ),
                          value: choice,
                          onTap: () {
                            print('Modal Bottom Sheet should open.');
                            showModalBottomSheet(
                              context: context,
                              builder: (context) {
                                return Container(
                                  color: Colors.transparent,
                                  height: 184,
                                );
                              },
                            );
                          },
                        ))
                    .toList())
          ],

Thank you for any help.


Solution

  • If you look in the PopupMenuItem documentation, you notice there is no onTap method. Instead, you should use PopupMenuButton's onSelected to detect taps, like this:

    actions: [
      PopupMenuButton(
        onSelected: _onChoiceSelected,
        itemBuilder: (BuildContext context) => choices.map((Choice choice) => PopupMenuItem<Choice>(
          child: Row(...),
          value: choice
        )).toList()
      )
    ]
    // ...
    void _onChoiceSelected(Choice choice) {
      showModalBottomSheet<void>(
        context: context,
        builder: (context) => Container(color: Colors.transparent, height: 184),
      );
    }