Automatically Close Drawer in Flutter Using GlobalKey

Drawers in Flutter conveniently display hidden content, typically for navigation or additional options or Automatically Close Drawer in Flutter Using GlobalKey. In most cases, drawers are opened and closed manually by the user. However, you might encounter situations where you want to programmatically toggle the drawer state, such as closing it automatically after a specific action or event.

In this blog, we will explore how to close a drawer in Flutter using an automatically GlobalKey<ScaffoldState> and a custom method to manage the drawer state.

Close Drawer in Flutter

Create a global key for ScaffoldState

First, we need to create a GlobalKey<ScaffoldState> to manage the drawer state. This key will allow us to access ScaffoldState and control the drawer programmatically.

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

Scaffold Key Close Drawer in Flutter

Next, assign the GlobalKey to the Scaffold widget’s key property. This enables us to control the drawer using the key.

Scaffold(
  key: _scaffoldKey,
  drawer: Drawer(
    // Add your drawer content here
  ),
  body: Center(
    child: ElevatedButton(
      onPressed: toggleDrawer,
      child: Text('Toggle Drawer'),
    ),
  ),
)

ToggleDrawer Method to Close Drawer in Flutter

Now, let’s implement the toggleDrawer method, which will handle both opening and closing the drawer. We will define two versions of the method, one for the left drawer and one for the right drawer.

Left Drawer – Close Drawer in Flutter

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

Right Drawer – Close Drawer in Flutter

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

Close the Drawer in Flutter Automatically

To automatically close the drawer after a specific action, such as tapping a button inside the drawer, you can use the same GlobalKey to close it. Here’s an example:

Drawer(
  child: ListView(
    padding: EdgeInsets.zero,
    children: [
      DrawerHeader(
        decoration: BoxDecoration(
          color: Colors.blue,
        ),
        child: Text('Header'),
      ),
      ListTile(
        title: Text('Item 1'),
        onTap: () {
          // Perform any action
          Navigator.pop(context); // Closes the drawer
        },
      ),
    ],
  ),
)

Alternatively, if you want to close the drawer automatically after opening it programmatically, you can add a delay:

void toggleDrawer() async {
  if (_scaffoldKey.currentState!.isDrawerOpen) {
    _scaffoldKey.currentState!.openEndDrawer();
  } else {
    _scaffoldKey.currentState!.openDrawer();
    await Future.delayed(Duration(seconds: 2)); // Adjust delay as needed
    _scaffoldKey.currentState!.openEndDrawer(); // Automatically closes the drawer
  }
}

Full code:

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Close Drawer Automatically Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: HomeScreen(),
    );
  }
}

class HomeScreen extends StatefulWidget {
  @override
  _HomeScreenState createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();

  void toggleDrawer() async {
    if (_scaffoldKey.currentState!.isDrawerOpen) {
      _scaffoldKey.currentState!.openEndDrawer();
    } else {
      _scaffoldKey.currentState!.openDrawer();
      await Future.delayed(Duration(seconds: 2)); // Adjust the delay as needed
      _scaffoldKey.currentState!.openEndDrawer(); // Automatically closes the drawer
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      key: _scaffoldKey,
      appBar: AppBar(
        title: Text('Flutter Drawer Demo'),
        leading: IconButton(
          icon: Icon(Icons.menu),
          onPressed: toggleDrawer,
        ),
      ),
      drawer: Drawer(
        child: ListView(
          padding: EdgeInsets.zero,
          children: <Widget>[
            DrawerHeader(
              decoration: BoxDecoration(
                color: Colors.blue,
              ),
              child: Text(
                'Header',
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 24,
                ),
              ),
            ),
            ListTile(
              title: Text('Item 1'),
              onTap: () {
                Navigator.pop(context); // Close the drawer on item tap
              },
            ),
            ListTile(
              title: Text('Item 2'),
              onTap: () {
                Navigator.pop(context); // Close the drawer on item tap
              },
            ),
          ],
        ),
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: toggleDrawer,
          child: Text('Toggle Drawer'),
        ),
      ),
    );
  }
}

Output:

Screenshot 2024 08 23 at 17.27.30

Also Read:

Conclusion

By using a GlobalKey<ScaffoldState>, you can control the drawer state in Flutter programmatically. Whether you need to toggle between opening and closing the drawer or automatically close it after a certain action, this approach provides the flexibility you need.

This method is particularly useful for creating smooth and user-friendly experiences in apps where the drawer plays a key role in navigation or displaying additional content.

Share:
Ambika Dulal

Ambika Dulal is a Flutter Developer from Nepal who is passionate about building beautiful and user-friendly apps. She is always looking for new challenges and is eager to learn new things. She is also a strong believer in giving back to the community and is always willing to help others.

Leave a Comment

AO Logo

App Override is a leading mobile app development company based in Kathmandu, Nepal. Specializing in both Android and iOS app development, the company has established a strong reputation for delivering high-quality and innovative mobile solutions to clients across a range of industries.

Services

UI/UX Design

Custom App Development

Mobile Strategy Consulting

App Testing and Quality Assurance

App Maintenance and Support

App Marketing and Promotion

Contact

App Override

New Plaza, Kathmandu