Doesn't disappear Drawer

Issue

When I go to different pages from the Drawer, this action is performed without problems and the menu on the new page disappears.

But when I return to the previous page, the menu remains open. I would like that when I press the back button and go to the previous page, the menu would disappear.

The back button is implemented in my AppBar and goes through the entire application.

    class CustomAppBar extends StatelessWidget implements PreferredSizeWidget {
  const CustomAppBar({Key? key}) : super(key: key);

  _goBack(BuildContext context) {
    Navigator.pop(context);
  }

  @override
  Size get preferredSize => const Size.fromHeight(kToolbarHeight);

  @override
  Widget build(BuildContext context) {
    return AppBar(
      leading:
      IconButton(
        icon: Icon(Icons.arrow_back_ios),
        iconSize: 20.0,
        splashRadius: 20,
        onPressed: () {
          _goBack(context);
        },
      ),
      iconTheme: IconThemeData(color: Colors.white, size: 40),
      backgroundColor: Colors.black,
      title: Image.asset("assets/images/it_logo_for_listdevices.png",
          width: 100, height: 50, color: Colors.white),
      centerTitle: true,
    );
  }
}

Drawer is also implemented as a separate file and goes through the entire application

    class HamburgerMenu extends StatelessWidget {
  const HamburgerMenu({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Drawer(
        child: ListView(
      children: [
        Container(
          height: 64.3,
          child: const DrawerHeader(
            decoration: BoxDecoration(
              color: Colors.black,
            ),
            child: Text(
              'Menu',
              style: TextStyle(
                color: Colors.white,
                fontSize: 30,
              ),
            ),
          ),
        ),
 .......

please tell me how to fix this error

Solution

Without your full code it’s pretty difficult to help, but I’m pretty sure this will do the trick:

In your drawer menu, change your Navigator.push to include a .then() with a Navigator.pop()

For example:

Navigator.push(
  context,
  MaterialPageRoute(builder: (context) => LoginPage()),
).then((value) => Navigator.pop(context));

The idea here is that the Navigator will push the new page then once the user returns the .then() is called, and the Navigator.pop() should close the current "top page" – which should be the drawer 👍

Answered By – Percent.twof

Answer Checked By – Mary Flores (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *