使用 showMenu() 时如何处理 PopupMeniItem 按下

ste*_*low 6 popupmenu flutter

我正在使用showMenu()来显示弹出菜单。通常,当您使用 PopupMenuButton 时,它具有onSelected选项,但您似乎没有使用 showMenu()。

我尝试将 PopupMenuItem 的内容包装在 GestureDetector 中,但这使得可点击区域太小了。见下图,较小的矩形是我的 GestureDetector(可以工作但太小),较大的矩形是 PopupMenuItem 附带的墨水池。

PopupMenuItem 中的 GestureDetector

所以我的问题是,当我没有 onSelected 属性时,我应该如何处理 PopupMenuItem 按下?

编辑:

这是代码。我有 ListTiles,它在 LongPress 上调用这个方法:

void _showOptionsMenu(int hiveIndex) {
    final RenderBox overlay = Overlay.of(context).context.findRenderObject();

showMenu(
  context: context,
  position: RelativeRect.fromRect(
    // magic code from stackoverflow, positions the PopupMenu on your tap location
    _tapPosition & Size(40, 40),
    Offset.zero & overlay.size,
  ),
  items: [
    PopupMenuItem(
      value: 0,
      child: Row(
        children: [
          Icon(Icons.edit),
          Text("Edit"),
        ],
      ),
    ),
    PopupMenuItem(
      value: 1,
      child: Row(
        children: [
          Icon(Icons.delete),
          Text("Delete"),
        ],
      ),
    ),
  ],
);
Run Code Online (Sandbox Code Playgroud)

您不能将 PopupMenuItems 包装在 GestureDetector 中,因为 items 属性只允许 PopupMenuItems。

Lon*_*olf 8

无需将项目包装到手势检测器中。显示菜单是一种异步方法,它返回项目菜单的值。当您按下任何项目时,您会返回该按下项目的值。有了这个价值,你就可以做任何你想做的事。检查这个代码

 Future<void> _showOptionsMenu(int hiveIndex) async {
    int selected = await showMenu(
      position: RelativeRect.fromLTRB(60.0, 40.0, 100.0, 100.0),
      context: context,
      items: [
        PopupMenuItem(
          value: 0,
          child: Row(
            children: [
              Icon(Icons.edit),
              Text("Edit"),
            ],
          ),
        ),
        PopupMenuItem(
          value: 1,
          child: Row(
            children: [
              Icon(Icons.delete),
              Text("Delete"),
            ],
          ),
        ),
      ],
    );
    if (selected == 0) {
      print('handle edit');
    } else {
      print('handle delete');
    }
  }
Run Code Online (Sandbox Code Playgroud)