Reputation: 3
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.
Upvotes: 0
Views: 33
Reputation: 434
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();
},
),
),
);
}
}
Upvotes: 0