DogeLion
DogeLion

Reputation: 3781

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

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

Upvotes: 85

Views: 76743

Answers (16)

Shakil Hossain
Shakil Hossain

Reputation: 21

As of flutter v3.27.X

To close the Scaffold's drawer after tapping an item use the following example

 if (Scaffold.of(context).isDrawerOpen) {
  Scaffold.of(context).closeDrawer();
}

Upvotes: 2

CHIRAG VORA
CHIRAG VORA

Reputation: 1

To close the Scaffold's drawer after an item tap, you can use the Navigator.pop(context) method. Here's an example of how you might use it:

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Drawer Example'),
      ),
      drawer: Drawer(
        child: ListView(
          padding: EdgeInsets.zero,
          children: <Widget>[
            DrawerHeader(
              child: Text('Drawer Header'),
              decoration: BoxDecoration(
                color: Colors.blue,
              ),
            ),
            ListTile(
              title: Text('Item 1'),
              onTap: () {
                // Do something when the item is tapped
                // Close the drawer
                Navigator.pop(context);
              },
            ),
            ListTile(
              title: Text('Item 2'),
              onTap: () {
                // Do something when the item is tapped
                // Close the drawer
                Navigator.pop(context);
              },
            ),
          ],
        ),
      ),
      body: Center(
        child: Text('Home Page'),
      ),
    );
  }
}

Upvotes: 0

Sampath Kumara
Sampath Kumara

Reputation: 1

Simply add Navigator.pop to your button or widget you tap

Navigator.pop(context);

Upvotes: 0

INSRAM UL HASSAN
INSRAM UL HASSAN

Reputation: 11

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

Upvotes: 1

sarjeet singh
sarjeet singh

Reputation: 541

 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();
                }
                ));
              },
            ),

Upvotes: 0

Bholendra Singh
Bholendra Singh

Reputation: 1156

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();
  }
}

Upvotes: 54

Pankhudi Software
Pankhudi Software

Reputation: 1

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(),
    );
  }
}

Upvotes: 0

Bhavesh Patel
Bhavesh Patel

Reputation: 596

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();

Upvotes: 1

Arun A
Arun A

Reputation: 21

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(),
   ),
  );
 }

Upvotes: -1

Yassine Chilali
Yassine Chilali

Reputation: 507

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();
}

Upvotes: 6

Chris
Chris

Reputation: 2034

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.

Upvotes: 3

CopsOnRoad
CopsOnRoad

Reputation: 267334

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()));

Upvotes: 21

Assaf S.
Assaf S.

Reputation: 4874

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

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

Upvotes: 35

Yann Masoch
Yann Masoch

Reputation: 1630

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.

Upvotes: 6

Collin Jackson
Collin Jackson

Reputation: 116698

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

Upvotes: 122

Related Questions