How to create a Drawer in flutter?

Hey, what’s up, guys. In this post, we will see how we can use a Drawer in Flutter that helps us in navigation.

Let’s see the steps and code to add a drawer to our app.

To create a drawer, follow these steps.

  1. First, we will create a Scaffold. Why? Because it supports some material design components such as Drawers, AppBars, and SnackBars that are specific to the scaffold.
  2. Add a drawer to the scaffold.
  3. Add items to the drawer
  4. After a user taps an item, close the drawer

Now let’s see the code.

class MyHomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text("Drawer Example"), backgroundColor: Colors.deepPurple,),
body: const Center(
child: Text('Flutter Drawer Example'),
),
drawer: Drawer(
// Add a ListView to the drawer.
child: ListView(
// Ensure that ListView doesn't have any padding.
// This line will Remove any padding from the ListView.
padding: EdgeInsets.zero,
children: [
DrawerHeader(
decoration: BoxDecoration(
color: Colors.deepPurple,
),
child: Image.asset("assets/images/mail.png")
),
ListTile(
title: const Text('Inbox'),
onTap: () {
// Here you can Update the state of the app,
//like, navigating to the screen the user has selected
// …
// After User has selected the option,
// close the drawer
Navigator.pop(context);
},
),
ListTile(
title: const Text('Sent Messages'),
onTap: () {
// Here you can Update the state of the app,
//like, navigating to the screen the user has selected
// …
// After User has selected the option,
// close the drawer
Navigator.pop(context);
},
),
],
),
),
);
}
}

(You can see the full code here – FlutterDrawerExample)

Output :

You can see in the above code that I have created a scaffold first and then added the drawer to the scaffold. Just one thing here – You can also use a Column widget to show the drawer items but using a ListView is much better because it allows you to scroll through the drawer if the items are more than the space available.

That’s all about Drawer in flutter.

Goodbye.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: