首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何从代码中显示PopupMenuButton菜单

如何从代码中显示PopupMenuButton菜单
EN

Stack Overflow用户
提问于 2019-05-18 12:50:09
回答 1查看 3K关注 0票数 2

当用户单击菜单时,PopupMenuButton会打开它。但是,如何从代码中在与PopupMenuButton相同的位置打开相同的菜单(例如,由于另一个用户事件)?

我试图在AppBar中创建一个嵌套菜单。就像当用户点击“按排序”时,菜单就会发生变化。还有其他方法可以做到这一点吗?我在网上找不到它。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-05-18 15:02:40

如果您查看PopupMenuButton,可以看到它使用的是showMenu方法,即使在按钮的上下文之外也是可以访问的(可能与导入的material Dart类一起出现)。

定义一个GlobalKey变量并将其应用到您的PopupMenuButton中,以获得按钮上下文的引用--这就是我们在屏幕上获取按钮位置的方法。

为菜单创建一个项目数组,然后在编程调用和物理按钮本身中重用它。

计算菜单出现的位置,然后进行showMenu调用。

showMenu返回一个未来-听它的完成,以获得选定的项目。

代码语言:javascript
复制
// Define these variables somewhere accessible by both the button on `build` & by the programmatic call.

final popupButtonKey = GlobalKey<State>(); // We use `State` because Flutter libs do not export `PopupMenuButton` state specifically.

final List<PopupMenuEntry> menuEntries = [
  PopupMenuItem(
    value: 1,
    child: Text('One'),
  ),
  PopupMenuItem(
    value: 2,
    child: Text('Two'),
  ),
];

在你的build

代码语言:javascript
复制
PopupMenuButton(
  key: popupButtonKey,
  initialValue: null,
  itemBuilder: (_) => menuEntries,
  // ...
);

要以编程方式显示菜单:

代码语言:javascript
复制
// Here we get the render object of our physical button, later to get its size & position
final RenderBox popupButtonObject = popupButtonKey.currentContext.findRenderObject();

// Get the render object of the overlay used in `Navigator` / `MaterialApp`, i.e. screen size reference
final RenderBox overlay = Overlay.of(context).context.findRenderObject();

// Calculate the show-up area for the dropdown using button's size & position based on the `overlay` used as the coordinate space.
final RelativeRect position = RelativeRect.fromRect(
  Rect.fromPoints(
    popupButtonObject.localToGlobal(Offset.zero, ancestor: overlay),
    popupButtonObject.localToGlobal(popupButtonObject.size.bottomRight(Offset.zero), ancestor: overlay),
  ),
  Offset.zero & overlay.size, // same as: new Rect.fromLTWH(0.0, 0.0, overlay.size.width, overlay.size.height)
);

// Finally, show the menu.
showMenu(
  context: context,
  elevation: 8.0, // default value
  items: menuEntries,
  initialValue: null,
  position: position,
).then((res) {
  print(res);
});
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56199101

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档