英文:
Do something before leaving page using navigation drawer menu icon
问题
在Flutter中,我有一些页面带有AppBar
,它显示导航抽屉的菜单图标,用于在不同页面之间导航。其中一些页面允许用户编辑一些数据。因此,当用户点击菜单图标而没有保存所做的编辑时,我想要请求确认,但我还没有找到一种方法来覆盖(相当于)导航菜单图标的onTap
。
在使用底部导航栏时有解决方案,还有一些可以检测页面已被弹出的解决方案,但我需要在关闭页面之前显示确认对话框。
英文:
In Fluter, I have some pages with an AppBar
that shows the menu icon of the navigation drawer that it is used to navigate among distinct pages. Some of this pages allow the user to edit some data. So, I would like to ask for confirmation when the user clicks the menu icon without saving the editions she has made, but I have not found a way to override the (equivalent to the) onTap
for the navigation menu icon.
There are solutions when a bottom navigation bar is used, and solutions that detect when the page has been popped, but I need the confirmation dialogue to be shown on the page being closed before the closing takes place.
答案1
得分: 0
这可以通过控制抽屉使用传递给Scaffold
的全局键(GlobalKey)以及明确指定AppBar
的leading
参数来简单完成:
class MyPage extends StatelessWidget {
MyPage({Key? key}) : super(key: key);
final _key = GlobalKey<ScaffoldState>();
@override
Widget build(BuildContext context) {
return Scaffold(
key: _key,
drawer: const Drawer(),
appBar: AppBar(
leading: DrawerButton(
onPressed: () async {
final state = _key.currentState;
final isOpen = state?.isDrawerOpen ?? false;
if (!isOpen) {
final close = await showDialog<bool>(
context: context,
builder: (context) => AlertDialog(
title: const Text('确定要关闭此页面吗?'),
actions: [
ElevatedButton(
onPressed: () => Navigator.of(context).pop(true),
child: const Text('关闭'),
)
],
),
);
if (close ?? false) state?.openDrawer();
return;
}
state?.closeDrawer();
},
),
),
);
}
}
如果还有其他需要翻译的内容,请提供并告诉我。
英文:
This can be done simply by controlling the drawer through the global key, passed to the Scaffold
, and specifying explicitly the leading
parameter of AppBar
:
class MyPage extends StatelessWidget {
MyPage({Key? key}) : super(key: key);
final _key = GlobalKey<ScaffoldState>();
@override
Widget build(BuildContext context) {
return Scaffold(
key: _key,
drawer: const Drawer(),
appBar: AppBar(
leading: DrawerButton(
onPressed: () async {
final state = _key.currentState;
final isOpen = state?.isDrawerOpen ?? false;
if (!isOpen) {
final close = await showDialog<bool>(
context: context,
builder: (context) => AlertDialog(
title:
const Text('Are you sure you want to close this page?'),
actions: [
ElevatedButton(
onPressed: () => Navigator.of(context).pop(true),
child: const Text('Close'),
)
],
),
);
if (close ?? false) state?.openDrawer();
return;
}
state?.closeDrawer();
},
),
),
);
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论