How to Open Drawer on Button Click in Flutter

In Flutter navigation drawer is an essential widget, we can use for easy navigation from the home screen in this article we are going to learn How to Open Drawer on Button Click in Flutter. Let's see an example step by step.

The first step is we need to use GlobalKey to open and close the Drawer.

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

Then we need to pass this key as Scaffold widget key like below

Scaffold(
   key: _scaffoldKey,
)

 

How to Open Drawer on Button Click in Flutter:

We can easily open the drawer using _scaffoldKey like below 

_scaffoldKey.currentState.openDrawer(),

 

How to Close Drawer on Button Click in Flutter:

We can easily close the drawer using _scaffoldKey like below 

_scaffoldKey.currentState!.closeDrawer();

 

Full Example:

You can see the full example below and you can use it in your project.

import 'package:flutter/material.dart';

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

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Errorgram',
      home: const Errorgram(title: 'Errorgram'),
    );
  }
}

class Errorgram extends StatefulWidget {
  const Errorgram({Key? key, required this.title}) : super(key: key);
  final String title;

  @override
  State<Errorgram> createState() => _ErrorgramState();
}

class _ErrorgramState extends State<Errorgram> {
  final GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey<ScaffoldState>();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        key: _scaffoldKey,
        drawer: Drawer(),
        appBar: AppBar(
          backgroundColor: Colors.red,
          title: Text("Errorgram"),
        ),
        body: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            ElevatedButton(
                onPressed: () {
                  _scaffoldKey.currentState!.openDrawer();
                },
                child: Text("Open Drawer")),
            SizedBox(
              width: 10,
            ),
            ElevatedButton(
                onPressed: () {
                  _scaffoldKey.currentState!.closeDrawer();
                },
                child: Text("Close Drawer"))
          ],
        ));
  }
}

 

Output:

You can see the output in the below screenshot.

Conclusion:

In this post, we learned How to Open Drawer on Button Click in Flutter and also see How to Close Drawer on Button Click in Flutter with an example. I hope this post may help you also you can find other interesting posts here.

 

Tags: