How to close Scaffold's drawer after an item tap?

DartFlutter

Dart Problem Overview


After I tap an item in the Scaffold's drawer I want it to automatically hide itself. How do I do it in Flutter?

Dart Solutions


Solution 1 - Dart

Navigator.pop() will pop the Drawer route off the stack and cause it to close.

Solution 2 - Dart

Solution 3 - Dart

First create a ScaffoldState key

GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey<ScaffoldState>();

Scaffold(
  key: _scaffoldKey,)

Now you can open and close the drawer using the toggleDrawer() method.

for the left drawer

toggleDrawer() async {
  if (_scaffoldKey.currentState.isDrawerOpen) {
    _scaffoldKey.currentState.openEndDrawer();
  } else {
    _scaffoldKey.currentState.openDrawer();
  }
}

for the right drawer

toggleDrawer() async {
  if (_scaffoldKey.currentState.isDrawerOpen) {
    _scaffoldKey.currentState.openDrawer();
  } else {
    _scaffoldKey.currentState.openEndDrawer();
  }
}

Solution 4 - Dart

Shorthand for closing the drawer and navigating to a new route:

Navigator.popAndPushNamed(context, '/newroute');

Solution 5 - Dart

If you simply want to close the Drawer, you can use any of the following:

Navigator.pop(context);
Navigator.of(context).pop();

And if you want to navigate to a new page, you can use

Navigator.popAndPushNamed(context, "/new_page");

or

Navigator.pop(context);
Navigator.push(context, MaterialPageRoute(builder: (_) => Page2()));

Solution 6 - Dart

For the lastest Flutter version (v0.3.2 when I am writing this), the implementation changed a bit and Navigator.pop() now requires a given context.

Navigator.pop(context) is the typical usage for closing a route.
Navigator.pop(context, true) is the usage for closing a route with a returned result.

See Drawer Class and example on Flutter's Cookbook.

Solution 7 - Dart

This is the answer

First in Class

GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey<ScaffoldState>();

Second In Widget

 Scaffold(key: _scaffoldKey,)

Third in code

if (_scaffoldKey.currentState.isDrawerOpen) {
  _scaffoldKey.currentState.openEndDrawer();
}

Solution 8 - Dart

I think what the OP is possibly trying to say is that even though Navigator.of(context).pop() and Navigator.pop(context) should work, they aren't in his case- I'm having the same issue.

Early on in a project the drawer works as it should - opening and closing properly. Since several changes have been made (none directly to the drawer or its scaffold) the drawer is no longer closing with Navigator.of(context).pop() and Navigator.pop(context).

I did a little more digging and found that instead of using Navigator.pop you can use Scaffold.of(context).openEndDrawer to close the drawer - even though it doesn't seem like it should. I've never used this function until now but it works perfectly. Hope this helps anyone with the same issue.

Solution 9 - Dart

You can use the below code according to your requirement.

When you want to remove and push new route:

Navigator.of(context).popAndPushNamed('/routeName');

When you want to just pop:

Navigator.of(context).pop();

Solution 10 - Dart

Well its quite Easy

Problem Statement : In default Home Page when someone presses back button , (if drawer is open) it is closed, else a prompt is thrown asking for Exit Application "Yes" and "No".

Solution

  1. Add

    GlobalKey _scaffoldKey = new GlobalKey();

  2. Make Function Future _onWillPop() async handling the required problem statement

  3. Call key and onWillPop as given in the below source code

See Through full source code For the additions done related to this problem statement in source code

import 'package:flutter/material.dart';

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey<ScaffoldState>();

  Future<bool> _onWillPop() async {
    if(_scaffoldKey.currentState != null && _scaffoldKey.currentState!.isDrawerOpen){
      return true;
    }
    return (await showDialog(
          context: context,
          builder: (context) => new AlertDialog(
            title: new Text('Leaving our App?'),
            content: new Text('Are you sure you want to Exit?'),
            actions: <Widget>[
              TextButton(
                onPressed: () => Navigator.of(context).pop(false),
                child: new Text('No'),
              ),
              TextButton(
                onPressed: () => Navigator.of(context).pop(true),
                child: new Text('Yes'),
              ),
            ],
          ),
        )) ??
        false;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      key: _scaffoldKey,
      body: WillPopScope(
        onWillPop: _onWillPop,
        child: Container(
          child: Center(
            child: Text("Welcome My App"),
          ),
        ),
      ),
      drawer: SideDrawer(),
    );
  }
}

Solution 11 - Dart

 ListTile(
              title: Text(
                'Notification Setting',
                style: TextStyle(
                    fontSize: 16.0, color: HexColor(HexColor.gray_text)),
              ),
              leading: Icon(
                Icons.notifications_outlined,
                size: 24.0,
                color: HexColor(HexColor.primarycolor),
              ),
              onTap: () {

                _scaffoldKey.currentState?.openEndDrawer();
                Navigator.push(context, MaterialPageRoute(builder: (context) {
                  return NotificationSettingActivity();
                }
                ));
              },
            ),

Solution 12 - Dart

First Pop widget, after that Push your route it will automatically close the Drawer when you come back next time.

Navigator.pop(context); // Widget will be poped
Navigator.pushNamed(context, '/routename'); // New Route will be pushed

Solution 13 - Dart

Navigate.of(context).pop(); OR
Navigate.pop(contex);

must be the first in onTap() function

for example :

 onTap: () {
 Navigator.of(context).pop();//before pushing to any other route 
 Navigator.push(
 context,
 MaterialPageRoute(
 builder: (BuildContext context) => Screen2(),
   ),
  );
 }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDogeLionView Question on Stackoverflow
Solution 1 - DartCollin JacksonView Answer on Stackoverflow
Solution 2 - DartHadrien LejardView Answer on Stackoverflow
Solution 3 - DartBholendra SinghView Answer on Stackoverflow
Solution 4 - DartAssaf S.View Answer on Stackoverflow
Solution 5 - DartCopsOnRoadView Answer on Stackoverflow
Solution 6 - DartYann MasochView Answer on Stackoverflow
Solution 7 - DartYassine ChilaliView Answer on Stackoverflow
Solution 8 - DartChrisView Answer on Stackoverflow
Solution 9 - DartBhavesh PatelView Answer on Stackoverflow
Solution 10 - DartPankhudi SoftwareView Answer on Stackoverflow
Solution 11 - Dartsarjeet singhView Answer on Stackoverflow
Solution 12 - DartINSRAM UL HASSANView Answer on Stackoverflow
Solution 13 - DartArun AView Answer on Stackoverflow