我试图在单击导航栏项目时显示菜单。这是我的尝试:
@override
Widget build(BuildContext context) {
return DefaultTabController(
length: 3,
child: Scaffold(
appBar: MyAppBar(
title: "Home",
context: context,
),
bottomNavigationBar: BottomNavigationBar(
items: [
BottomNavigationBarItem(
icon: new Icon(Icons.home), title: Text('Home')),
BottomNavigationBarItem(
icon: new Icon(Icons.book), title: Text('Second')),
BottomNavigationBarItem(
icon: new PopupMenuButton(
icon: Icon(Icons.add),
itemBuilder: (_) => <PopupMenuItem<String>>[
new PopupMenuItem<String>(
child: const Text('test1'), value: 'test1'),
new PopupMenuItem<String>(
child: const Text('test2'), value: 'test2'),
],
),
title: Text('more')),
],
currentIndex: 0,
),
body: new Container()));
}
我遇到了两个问题。第一个是 NavigationBarItem 的显示。 icon
和 title
之间有一个我无法删除的填充(即使通过添加 padding: EdgeInsets.all(0.0)
)(如下图显示)。第二个是我需要准确地单击图标才能显示菜单。
当 index=2
的 BottomNavigationBarItem
时,我尝试直接调用 showMenu
(PopupMenuButton
调用的方法) (例如)被点击。但是如何确定菜单应该从哪里出现是很棘手的。
最佳答案
这里尝试直接使用 showMenu
并调用函数 buttonMenuPosition
来获取菜单的位置。它相当脆弱,但您可以将按钮的位置更改到中间,例如使用 bar.size.center
而不是 bar.size.bottomRight
。使用一些 MATH 并通过手动操作 Offset
对象(如果/当您有超过 3 个项目时),您可以更改位置以将菜单放在没有的项目上中心或末端)。
RelativeRect buttonMenuPosition(BuildContext c) {
final RenderBox bar = c.findRenderObject();
final RenderBox overlay = Overlay.of(c).context.findRenderObject();
final RelativeRect position = RelativeRect.fromRect(
Rect.fromPoints(
bar.localToGlobal(bar.size.bottomRight(Offset.zero), ancestor: overlay),
bar.localToGlobal(bar.size.bottomRight(Offset.zero), ancestor: overlay),
),
Offset.zero & overlay.size,
);
return position;
}
@override
Widget build(BuildContext context) {
final key = GlobalKey<State<BottomNavigationBar>>();
return DefaultTabController(
length: 3,
child: Scaffold(
appBar: AppBar(
title: Text("Home"),
),
bottomNavigationBar: BottomNavigationBar(
key: key,
items: [
const BottomNavigationBarItem(
icon: Icon(Icons.home), title: Text('Home')),
const BottomNavigationBarItem(
icon: Icon(Icons.book), title: Text('Second')),
const BottomNavigationBarItem(
icon: Icon(Icons.add), title: Text('more')),
],
currentIndex: 0,
onTap: (index) async {
final position = buttonMenuPosition(key.currentContext);
if (index == 2) {
final result = await showMenu(
context: context,
position: position,
items: <PopupMenuItem<String>>[
const PopupMenuItem<String>(
child: Text('test1'), value: 'test1'),
const PopupMenuItem<String>(
child: Text('test2'), value: 'test2'),
],
);
}
},
),
body: Container()));
}
关于dart - Flutter - 在 BottomNavigationBar 中显示一个 PopupMenuButton,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53337506/