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

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

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

这是我在 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),
  );
}