How to Create a Side menu in Flutter
Welcome to another blog on Flutter. In this blog, I’ll show you how you can easily create a side menu in Flutter which is also referred to as Navigation bar. Also, I assume that you have a little knowledge about Flutter however, I’ll try to explain as much as possible. So let’s just dive into the code!
This is how it will look at the end:
1. Create a Flutter project
Create a new Flutter project by the following command you can name it whatever you like:
$ flutter create side_menu_app
The above command will create a default counter-based application for you. Open the project folder in your preferred editor. I choose VS Code.
2. Create a Simple Page
In the main.dart file, remove everything that’s there by default. We’re going to build from scratch. Below is the code for our updated main.dart file:
Now let’s understand what’s going on here. First, we imported the main Flutter library(material.dart) and then our navbar widget which we’ll see in a while, then we have our main function that will bootstrap the app.
Tip: It’s a good practice to place all library imports at the very beginning of the file and then your own created widgets and separate them with an empty line.
First, you’ll create a simple Stateless App widget which will return MaterialApp. Within this, we’ve set MyHomePage as home which will be displayed when the app starts.
MyHomePage is again a Stateless widget that returns a Scaffold. You can think of it as a visible area which covers the whole screen. It may have an App bar on the top main content in the middle or bottom navigation at the end.
To show the navbar, we have provided a NavDrawer(discussed in step 3) to the drawer attribute of the AppBar.
Flutterdrawer: NavDrawer()
3. Create Side menu Widget
Now, inside your lib folder, create a new folder ‘widgets’. It’s a good idea to keep widgets reusable and organized from the very start. Here’s the code:
This NavDrawer returns a special widget, Drawer which contains a ListView. This ListView contains all the links that you want the user to navigate around. Notice that the first widget is a DrawerHeader in which we have a title text and a background image. This is completely optional. If you don’t want this header, simply remove this from the list.
Next, we have multiple ListTile widgets. Each ListTile contains a leading icon, title and a listener (onTap). The listener here is doing nothing except for dismissing the navbar with the following line of code:
Navigator.of(context).pop()
I’ll discuss Navigation & in detail in my upcoming blog so stay tuned for more :)