当用户单击菜单时,PopupMenuButton会打开它。但是,如何从代码中在与PopupMenuButton相同的位置打开相同的菜单(例如,由于另一个用户事件)?
我试图在AppBar中创建一个嵌套菜单。就像当用户点击“按排序”时,菜单就会发生变化。还有其他方法可以做到这一点吗?我在网上找不到它。
发布于 2019-05-18 15:02:40
如果您查看PopupMenuButton,可以看到它使用的是showMenu方法,即使在按钮的上下文之外也是可以访问的(可能与导入的material Dart类一起出现)。
定义一个GlobalKey变量并将其应用到您的PopupMenuButton中,以获得按钮上下文的引用--这就是我们在屏幕上获取按钮位置的方法。
为菜单创建一个项目数组,然后在编程调用和物理按钮本身中重用它。
计算菜单出现的位置,然后进行showMenu调用。
showMenu返回一个未来-听它的完成,以获得选定的项目。
// 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里
PopupMenuButton(
key: popupButtonKey,
initialValue: null,
itemBuilder: (_) => menuEntries,
// ...
);要以编程方式显示菜单:
// 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);
});https://stackoverflow.com/questions/56199101
复制相似问题