vellai durai
vellai durai

Reputation: 1011

How to open drawer programatically on press in flutter

I need to open app drawer while clicking floating button, but its not opening. Kindly suggest if there is any other thing other than drawer i am looking to build filter section

here is my part of the code

 final GlobalKey<ScaffoldState> _scaffoldKey =
      new GlobalKey<ScaffoldState>(); // 
 drawer: Drawer(
        // Add a ListView to the drawer. This ensures the user can scroll
        // through the options in the drawer if there isn't enough vertical
        // space to fit everything.
        child: ListView(
          // Important: Remove any padding from the ListView.
          padding: EdgeInsets.zero,
          children: <Widget>[
            DrawerHeader(
              child: Text('Drawer Header'),
              decoration: BoxDecoration(
                color: Colors.blue,
              ),
            ),
            ListTile(
              title: Text('Item 1'),
              onTap: () {
                // Update the state of the app
                // ...
                // Then close the drawer
                Navigator.pop(context);
              },
            ),
            ListTile(
              title: Text('Item 2'),
              onTap: () {
                // Update the state of the app
                // ...
                // Then close the drawer
                Navigator.pop(context);
              },
            ),
          ],
        ),
      ),
      
      floatingActionButton: FloatingActionButton.extended(
          onPressed: () {
            // Add your onPressed code here!

            _scaffoldKey.currentState.openDrawer();
           
          },
          label: Text(
            'Filter',
            style:
                TextStyle(decoration: TextDecoration.none, color: Colors.black),
          ),
          icon: Icon(Icons.filter_alt, color: Colors.black),
          backgroundColor: Colors.white),

I am getting error

Another exception was thrown: NoSuchMethodError: The method 'openDrawer' was called on null.

Upvotes: 0

Views: 579

Answers (2)

bcihan
bcihan

Reputation: 317

You should pass _scaffoldKeyparamater to your scaffold.

Scaffold(key: _scaffoldKey);

Upvotes: 1

Amit Kumar
Amit Kumar

Reputation: 307

Actually you have to set key property in scaffold.

Scaffold(key:_scaffoldKey)

Then use same method as you are using.

Upvotes: 0

Related Questions