【发布时间】:2021-12-08 13:27:35
【问题描述】:
我曾经使用 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,
),
)
],
)
)
);
}
【问题讨论】:
-
您可以尝试将
context从itemBuilder传递到_openSettings()吗?所以你可以将正确的context传递给导航器
标签: flutter dart flutter-navigation