Reputation: 658
I am looking to open and close a drawer programmatically when I press on an icon. I am trying to use keys, but I am not having much luck. I found this article - Flutter: How to open Drawer programmatically ,but I am having issues.
I have a column of icons (see screenshot) that I include in one file and my drawer is in another, both of which are obviously included in a third (which is a fullscreen google map). I am looking at using a global key, but I am unsure where to put everything.
In my map page I have
class _TheMapState extends State<TheMap> with WidgetsBindingObserver {
GlobalKey<ScaffoldState> _drawerKey = GlobalKey();
...
...
When I try to add the key in my drawer page, it doesn't recognise it, so I add the GlobalKey line to my drawer page. I also have to do that to my icon options page too, otherwise the app won't build, due to the errors. There are no errors when I do this, but nothing happens when I click on the button.
Here is where I added the key to the drawer.
Widget mapDrawer() {
return Drawer(
key: _drawerKey,
...
...
Here is my icon code, which is in a separate file.
Widget _buildShowHideDrawerIcon() {
return Container(
child: Opacity(
opacity: 0.60,
child: Container(
padding: EdgeInsets.all(7.0),
decoration: BoxDecoration(
color: Colors.white,
//border: Border.all(color: Colors.black12, width: 1.0),
boxShadow: [
BoxShadow(
color: Colors.black,
offset: Offset(0.0, 0.0),
blurRadius: 3.0,
),
],
),
child: InkWell(
onTap: () {
print("SHOW/HIDE DRAWER ICON PRESSED");
setState(() {
_drawerKey.currentState.openDrawer();
});
},
child: Icon(
Icons.swap_horiz,
color: Colors.black87,
size: 24.0,
semanticLabel: 'Show ,or hide sliding drawer',
),
),
),
),
);
}
I would appreciate any help on this.
Upvotes: 0
Views: 1910
Reputation: 132
You should assign the key to Scaffold
, not Drawer
Scaffold(
key: _drawerKey,
And replace the line:
_drawerKey.currentState.openDrawer();
With
_drawerKey.currentState?.openDrawer();
Upvotes: 0
Reputation: 3488
Assign the key to Scaffold
, not Drawer
Scaffold(
key: _drawerKey,
drawer: Drawer(),
Upvotes: 0