我曾经使用 IconButton 的 onpressed 从我的 AppBar 导航到设置页面,这很有效。 现在我正尝试从 PopupMenuItem 的 onTap 触发导航,但页面不导航。两个小部件都在同一层次结构中,我无法找出不同行为的原因。不会抛出任何错误。
这是我的 appBar 的代码,其中包含操作:
Widget build(BuildContext ctx) {
return Container(
child: Scaffold(
appBar: AppBar(
title: const Text('MyApp'),
actions: [
PopupMenuButton(
itemBuilder: (context) => [
// THE NAVIGATION IN onTap DOES NOT WORK
PopupMenuItem(
child: Text(AppLocalizations.of(context).settings),
onTap: () => _openSettings(ctx),
),
],
icon: Icon(
Icons.settings,
),
),
// THIS WORKS
IconButton(onPressed: () => _openSettings(ctx),
icon: Icon(Icons.settings))
],
),
body: Text("")
),
);
}
这里的导航调用仅在 IconButton 的 onpressed 内部起作用。 不过,我可以确认在这两种情况下都触发了该功能:
Future<void> _openSettings(BuildContext ctx) async {
print('settings');
await Navigator.push(
ctx, MaterialPageRoute(builder: (ctx) => SettingsPage()));
print('settings completed');
}
如果有任何帮助,我将不胜感激!
解决方法: 我还没有发现 onTap 导航的问题是什么,但现在我只使用 onSelected,它会产生相同的用户体验和工作方式:
Widget build(BuildContext ctx) {
return Container(
child: Scaffold(
appBar: AppBar(
title: const Text('MyApp'),
actions: [
PopupMenuButton(
onSelected: (result){
switch(result){
case 0: _openSettings(); break;
case 1: _signOut(); break;
}
},
itemBuilder: (context) => [
PopupMenuItem(
child: Text(AppLocalizations.of(context).settings),
value: 0
),
PopupMenuItem(
child: Text(AppLocalizations.of(context).logout),
value: 1
)
],
icon: Icon(
Icons.settings,
),
)
],
)
)
);
}
最佳答案
我有同样的问题(除了:我正在使用 GetX 进行导航。
我认为发生这种情况是因为 flutter 会自动关闭 PopupMenuButton,并且由于导航速度很快,它会关闭新路由而不是 menuButton。
我在导航方法中是这样解决的:
void edit() async {
await Future.delayed(const Duration(milliseconds: 10));
Get.toNamed('/new/route'); // same like Navigator.of(context).pushNamed()
}
它并不漂亮……我知道。但它有效 XD
关于Flutter - 在 PopupMenuButton onTap 中导航不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69667774/