Flutter Modal Bottom Sheet 不适用于 AppBar 内的弹出菜单按钮

问题描述

我遇到的问题是方法“showModalBottomSheet”在弹出菜单项的“onTap”函数中不起作用。单击弹出菜单条目时,模态底部工作表未显示

这是我在 AppBar 的 actions 参数中的代码

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())
          ],

感谢您的帮助。

解决方法

如果您查看 PopupMenuItem 文档,您会注意到没有 onTap 方法。相反,您应该使用 PopupMenuButtononSelected 来检测点击,如下所示:

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