You are currently viewing Flutter NavigationDrawer Tutorial and Examples

Flutter NavigationDrawer Tutorial and Examples

Flutter Navigation Drawer Tutorial and Example

This is a flutter navigation drawer tutorial with a full example. We start by discussing what navigation drawer is, when to use then look at a full example with fragments containing gridviews.

What is a Navigation Drawer?

A NavigationDrawer is a widget that allows us render navigation items in a sidebar with an optional user account profile. Navigation Drawer usually renders items in a ListView or ExpandableList. It usually has a header where we can display user account details like name, email, profile avatar et.

When a single navigation drawer item is clicked you navigate to a page or what we are calling fragments in this case.

When to use NavigationDrawer

Use navigation drawer when you have more items than can fit comfortably in a tabbar or bottomnavigation. Or if you find navigation drawer more intuitive to use of course.

Let's look at some standalone full examples.

Example 1. Flutter Navigation Drawer - Fragments with GridViews

We will explore an example where we will render a navigation drawer with header containing user name, email as well as avatar. We will show a user image as avatar. We will also show a navigation drawer background image.

Flutter NavigationDrawer GridView

Flutter NavigationDrawer

Then when the user clicks a single navigation drawer item we will open an associated fragment or page. That fragment will contain gridviews with some data.

We have three files:

  1. Fragments.dart - To define our Fragment classes. These are just stateless widgets.
  2. Home.dart - This is our home page. It's also where we define our navigation drawer.
  3. main.dart - The classic main file with our main method. Entry point to our application.
(a). Fragments.dart
import 'package:flutter/material.dart';
  //Let's create a reusable method that can render GridView as long as it passed a
  //a BuildContext as well as list of strings
  Widget createGridView(BuildContext context,List<String> cosmicBodies) {
    //I will shuffle my data
    cosmicBodies.shuffle();
   // Then build my GridView and return it
    return new GridView.builder(
      itemCount: cosmicBodies.length,
      gridDelegate: new SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2),
      itemBuilder: (BuildContext context, int index) {
        return new GestureDetector(
          child: new Card(
            elevation: 5.0,
            child: new Container(
              alignment: Alignment.centerLeft,
              margin: new EdgeInsets.only(top: 10.0, bottom: 10.0,left: 10.0),
              child: new Text(cosmicBodies[index]),
            ),
          ),
    );
    }
    );
  }
//Create Meteors Fragment. This will contains a gridview with our meteors
class Meteors extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    var meteors = ["Tunguska","Crab Pulsar","Geminga","Calvera","Vela X-1","Gaspra",
    "Psyche","Pallas","Ceres","Pioneer","Haumea","Makemake","Eris"];
    return createGridView(context, meteors);
  }
}
//Create Moons Fragment. This will contains a gridview with our moons
class Moons extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    var moons =  ["Phobos","Deimos","Moon","Triton","Proteus","Oberon","Umbriel","Ariel","Titan",
    "Rhea","Lapetus","Dione","Enceladus","Mimas","Ganymede","Callisto","IO","Europa"];
    return createGridView(context, moons);
  }
}
//Create Stars Fragment. This will contains a gridview with our stars
class Stars extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    var stars = ["UY Scuti","VY Cani Majoris","VV Cephei","KY Cygni","Aldebaran","Canopus",
    "Sirius","Vega","Alpha Pegasi","Bellatrix","Pollux","Betelgeuse","Naos","Arcturus","Polaris",
      "Rigel","Deneb","Wezen","Antares","Eya Caninae"];
    return createGridView(context, stars);
  }
}
//Create Galaxies Fragment. This will contains a gridview with our galaxies
class Galaxies extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    var galaxies = ["Messier 87","Andromeda","Sombrero","Whirlpool","Pinwheel","Milky Way",
    "Cartwheel", "Black Eye Galaxy","Star Bust","Centaurus","Triangulum","Sunflower",
    "Caldwell","Tadpole","Hoag's Object","Mallin 1","NGC 262","IC 1101"];
    return createGridView(context, galaxies);
  }
}
(b). Home.dart
import 'package:mr_nav_drawer/pages/Fragments.dart' as Fragments;
import 'package:flutter/material.dart';
//Let's define a DrawerItem data object
class DrawerItem {
  String title;
  IconData icon;
  DrawerItem(this.title, this.icon);
}
// Our Homepage
class HomePage extends StatefulWidget {
  //Let's define our drawer items, strings and images
  final drawerItems = [
    new DrawerItem("Meteors", Icons.strikethrough_s),
    new DrawerItem("Moons", Icons.place),
    new DrawerItem("Stars", Icons.stars),
    new DrawerItem("Galaxies", Icons.gavel)
  ];
  //Let's Create and Return state for this 'StatefulWidget'
  @override
  State<StatefulWidget> createState() {
    return new HomePageState();
  }
}
// Let's define state for our homepage. A state is just information for a widget.
class HomePageState extends State<HomePage> {
  int _selectedDrawerIndex = 0;
  //Let's use a switch statement to return the Fragment for a selected item
  _getDrawerFragment(int pos) {
    switch (pos) {
      case 0:
        return new Fragments.Meteors();
      case 1:
        return new Fragments.Moons();
      case 2:
        return new Fragments.Stars();
      case 3:
        return new Fragments.Galaxies();
      default:
        return new Text("Error");
    }
  }
  //Let's update the selectedDrawerItemIndex the close the drawer
  _onSelectItem(int index) {
    setState(() => _selectedDrawerIndex = index);
    //we close the drawer
    Navigator.of(context).pop();
  }
  @override
  Widget build(BuildContext context) {
    List<Widget> drawerOptions = [];
    //Let's create drawer list items. Each will have an icon and text
    for (var i = 0; i < widget.drawerItems.length; i++) {
      var d = widget.drawerItems[i];
      drawerOptions.add(
        new ListTile(
          leading: new Icon(d.icon),
          title: new Text(d.title),
          selected: i == _selectedDrawerIndex,
          onTap: () => _onSelectItem(i),
        )
      );
    }
    //Let's scaffold our homepage
    return new Scaffold(
      appBar: new AppBar(
        // We will dynamically display title of selected page
        title: new Text(widget.drawerItems[_selectedDrawerIndex].title),
      ),
      // Let's register our Drawer to the Scaffold
      drawer: new Drawer(
        child: new Column(
          children: <Widget>[
            //Lets Create a material design drawer header with account name, email,avatar
            new UserAccountsDrawerHeader(
                accountName: new Text("Oclemy"),
                accountEmail: new Text("[email protected]"),
                currentAccountPicture: new CircleAvatar(backgroundImage:
                 new AssetImage("assets/profile.png"),),
            decoration: new BoxDecoration(
              image: new DecorationImage(
                image: new AssetImage("assets/bg.jpg"),
                fit: BoxFit.cover
              )
            ),
                ),
            new Column(children: drawerOptions)
          ],
        ),
      ),
      body: _getDrawerFragment(_selectedDrawerIndex),
    );
  }
}
(c). main.dart
import 'package:mr_nav_drawer/pages/Home.dart';
import 'package:flutter/material.dart';
//Lastly we come to our main app
class MyApp extends StatelessWidget {
  // This is the root of our application.
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Mr NavigationDrawer',
      theme: new ThemeData(
        primarySwatch: Colors.deepOrange,
      ),
      home: new HomePage(),
    );
  }
}
//Then we run our app
void main() => runApp(new MyApp());

Download the source code here.

Example 2: NavigationDrawer - Switch through pages

This is also another NavigationDrawer suitable for beginners.There are two pages and you can switch through them via the navigationdrawer menu items.

Of course you can add more pages. Here is demo:

Flutter NavigationDrawer Example

Step 1: Create Project

Start by creating an empty Flutter project.

Step 2: Dependencies

No special or third party dependencies are needed. We have everything we need in the material package.

Step 3: Create Two Pages

We will be switching through these two via the NavigationDrawer component:

(a). otherpage.dart

Just a simple StatelessWidget with a Text widget at the center:

import "package:flutter/material.dart";
class OtherPage extends StatelessWidget{
  final String pageTextChanged;
  OtherPage(this.pageTextChanged);
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text(pageTextChanged),),
      body: Center(
        child: Text(pageTextChanged),
      ),
    );
  }
}

(b). homepage.dart

This is where we construct our NavigationDrawer so it involves more code. The NavigationDrawer will be constructed based on the ListTile objects.

Here is the full code

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import './otherpage.dart';
class HomePage extends StatefulWidget{
  @override
  State<StatefulWidget> createState() {
    return _HomePage();
  }
}
class _HomePage extends State<HomePage>{
  String mainProfilePic = "https://images.pexels.com/photos/220453/pexels-photo-220453.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500";
  String otherProfilePic = "https://img.rawpixel.com/s3fs-private/rawpixel_images/website_content/368-mj-2516-02.jpg?w=800&dpr=1&fit=default&crop=default&q=65&vib=3&con=3&usm=15&bg=F4F4F3&ixlib=js-2.2.1&s=9f3d0ad657bbca1c0f2db36ad7deb323";
  //.. Switching Profile using multiple Accounts
  /*void switchUser(){
    String backupString = mainProfilePic;
    this.setState(() {
      mainProfilePic = otherProfilePic;
      otherProfilePic = backupString;
    });
  }*/
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("Navigation Drawer"),),
      drawer: new Drawer(
        child:  ListView(
        children: <Widget>[
          UserAccountsDrawerHeader(
            accountName: Text("John Doe"),
            accountEmail: Text("[email protected]"),
            currentAccountPicture: GestureDetector(
               child: CircleAvatar(
                 backgroundImage: NetworkImage(mainProfilePic),
               ),
              onTap: () => print("Current User")
            ),
           //.. This line of code provides the usage of multiple accounts
           /* otherAccountsPictures: <Widget>[
              GestureDetector(
                onTap: ()=> switchUser(),
                child: CircleAvatar(
                  backgroundImage: NetworkImage(otherProfilePic)
                ),
              ),
            ], */
            decoration: BoxDecoration(
              image: DecorationImage(
            fit: BoxFit.fill,
                  image: NetworkImage("https://png.pngtree.com/thumb_back/fh260/background/20190828/pngtree-dark-vector-abstract-background-image_302715.jpg")
             ),
            ),
          ),
           ListTile(
            title: Text("Home Page"),
             trailing: Icon(Icons.menu),
             onTap: () {
              Navigator.of(context).pop();
               Navigator.of(context).push(new MaterialPageRoute(builder:
                   (BuildContext context) => OtherPage("Home Page"),
               ));
             }
          ),
          ListTile(
            title: Text("About Page"),
            trailing: Icon(Icons.info),
              onTap: () {
                Navigator.of(context).pop();
                Navigator.of(context).push(new MaterialPageRoute(builder:
                    (BuildContext context) => OtherPage("About Page"),
                ));
              }
          ),
          ListTile(
            title: Text("Settings Page"),
            trailing: Icon(Icons.security),
              onTap: () {
                Navigator.of(context).pop();
                Navigator.of(context).push(new MaterialPageRoute(builder:
                    (BuildContext context) => OtherPage("Settings Page"),
                ));
              }
          ),
          Divider(thickness: 1.0,),
          ListTile(
            title: Text("Close"),
            trailing: Icon(Icons.cancel),
            onTap: () => Navigator.of(context).pop(),
          ),
        ],
        )
    )
    );
  }
}

Step 5: main class

Now come create the main class where we run our app:

import 'package:flutter/material.dart';
import 'package:flutter_side_menu_drawer/screens/homepage.dart';
 void main()=> runApp(
    MaterialApp(
     debugShowCheckedModeBanner: false,
    home: HomePage()
)
);

Run

Copy the code or download it in the link below, build and run.

Reference

Here are the reference links:

Number Link
1. Download Example
2. Follow code author

Example 3: Animated Drawer Example

This example teaches you how to animate a drawer in flutter. The drawer is a basic one with only basic Texts as menu items.

Here is the demo:

Flutter Animated Drawer

Step 1: Create Project

Start by creating an empty Flutter project.

Step 2: Dependencies

No third party dependencies are needed.

Step 3: Create a StackView

Here is the full code:

stackView.dart

import 'package:flutter/material.dart';
import "animUtil.dart";
class MainActivity extends StatefulWidget {
  AnimationController _controller;
  MainActivity(this._controller);
  @override
  _MainActivityState createState() => _MainActivityState();
}
class _MainActivityState extends State<MainActivity> {
  static String _superHeroName = "CaptainAmerica";
  void animate(String hero) {
    setState(() {
      _superHeroName = hero;
    });
    _startAnimation(widget._controller);
  }
  void _backViewOnClick(int position) {
    switch (position) {
      case 0:
        animate("Captain America");
        break;
      case 1:
        animate("Iron Man");
        break;
      case 2:
        animate("Thor");
        break;
      case 3:
        animate("Hulk");
        break;
      default:
    }
  }
  Widget activityContainer(BuildContext context, BoxConstraints constraint) {
    final ThemeData _theme = Theme.of(context);
    return Container(
      child: Stack(
        children: <Widget>[
          _backView(_theme),
         _frontView()],
      ),
    );
  }
  Widget _backView(ThemeData theme) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: theme.backgroundColor,
        elevation: 0.0,
      ),
      backgroundColor: theme.backgroundColor,
      body: Container(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            MaterialButton(
              onPressed: () => _backViewOnClick(0),
              child: Text("Captain America", style: TextStyle(fontSize: 30)),
            ),
            MaterialButton(
              onPressed: () => _backViewOnClick(1),
              child: Text(
                "Iron Man",
                style: TextStyle(fontSize: 30),
              ),
            ),
            MaterialButton(
              onPressed: () => _backViewOnClick(2),
              child: Text(
                "Thor",
                style: TextStyle(fontSize: 30),
              ),
            ),
            MaterialButton(
              onPressed: () => _backViewOnClick(3),
              child: Text(
                "Hulk",
                style: TextStyle(fontSize: 30),
              ),
            )
          ],
        ),
      ),
    );
  }
/*
Frontview body is wrappped by SlideTransition and ScaleTransition.
Alignment is set to centerLeft inorder to show navigation back button.
*/
  Widget _frontView() {
    return SlideTransition(
        position: _getSlideAnimation(),
        child: ScaleTransition(
          alignment: Alignment.centerLeft,
          scale: _getScaleAnimation(),
          child: _frontViewBody(),
        ));
  }
  Widget _frontViewBody() {
    return Scaffold(
      appBar: AppBar(
        title: Text("Avengers"),
        backgroundColor: Colors.purple,
        leading: IconButton(
          onPressed: () => _startAnimation(widget._controller),
          icon: AnimatedIcon(
            icon: AnimatedIcons.arrow_menu,
            progress: widget._controller,
          ),
        ),
      ),
      body: Container(
        child: Column(
          children: <Widget>[
            Expanded(
              child: Container(
                child: Center(
                  child: Text(
                    _superHeroName,
                    style: TextStyle(fontSize: 30, color: Colors.red),
                  ),
                ),
              ),
            )
          ],
        ),
      ),
    );
  }
  void _startAnimation(AnimationController _controller) {
    _controller.fling(
        velocity: AnimUtil.isBackpanelVisible(widget._controller) ? -1.0 : 1.0);
  }
  @override
  Widget build(BuildContext context) {
    return LayoutBuilder(
      builder: activityContainer,
    );
  }
/*
FrontView Slide Animation
*/
  Animation<Offset> _getSlideAnimation() {
    return Tween(begin: Offset(0.85, 0.0), end: Offset(0, 0)).animate(
        CurvedAnimation(parent: widget._controller, curve: Curves.linear));
  }
/*
Front View Scale Animation
*/
  Animation<double> _getScaleAnimation() {
    return Tween(begin: 0.7, end: 1.0).animate(
        CurvedAnimation(parent: widget._controller, curve: Curves.linear));
  }
}

Step 4: Create Animation Utils

Create animUtil.dart and add the following code;

animUtil.dart


import 'package:flutter/animation.dart';
 class AnimUtil{
static bool isBackpanelVisible(AnimationController _controller) {
    final AnimationStatus status =_controller.status;
    return status == AnimationStatus.completed ||
        status == AnimationStatus.forward;
  }
  }

Step 5: Create main class

Here is the main class code:

main.dart

import 'package:custom_navigation_drawer/stackView.dart';
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Custom Navigation Drawer',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}
class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage>
    with SingleTickerProviderStateMixin {
  AnimationController _controller;
  @override
  void initState() {
    super.initState();
    _controller = AnimationController(
        vsync: this, duration: const Duration(milliseconds: 100), value: 1.0);
  }
  @override
  void dispose() {
    super.dispose();
    _controller.dispose();
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: MainActivity(_controller),
    );
  }
}

Run

Copy the code or download it in the link below, build and run.

Reference

Here are the reference links:

Number Link
1. Download Example
2. Follow code author

Example 4: Flutter Dual Drawer

This example teaches you how to create an app with two NavigationDrawers: one on the left and the other on the right.

Below is the screenshot of the app:


Step 1: Create Project

Start by creating an empty Flutter project.

Step 2: Dependencies

No third party library is needed.

Step 3: Add Assets

Assets are static resources you may want to use in the app. For example in this case we have the profile and background images we want to use in our NavigationDrawer. We have to add them in the assets folder.

Then in the pubspec.yaml you add the following:

  # To add assets to your application, add an assets section, like this:
  assets:
    - assets/profile.png
    - assets/bg.jpg
    - assets/bg_2.jpg
    - assets/profile_2.jpg

Step 4: Write Co

Replace your main.dart code with the following:

main.dart

import 'package:flutter/material.dart';
 void main()=>runApp(
   new MaterialApp(
 home: new home(),
 debugShowCheckedModeBanner: false,
   )
 );
 class home extends StatefulWidget {
   @override
   _homeState createState() => new _homeState();
 }
 class _homeState extends State<home> {
   @override
   Widget build(BuildContext context) {
     return new Scaffold(
    appBar: new AppBar(
      title: new Center(
        child: new Text("Navigation Drawer"),
      ),
    ),
    drawer: new Drawer(
      child:new my_drawer(
        email: "[email protected]",
        name: "Abdi hamid",
        profileimg: "assets/profile.png",
        background: "assets/bg.jpg",
      )
    ),
    endDrawer: new Drawer(
       child: new my_drawer(
      email: "[email protected]",
      name: "John doe",
      profileimg: "assets/profile_2.jpg",
      background: "assets/bg_2.jpg",
    ),
    ),
    body: new Center(
      child: new Text("Drawer"),
    ),
     );
   }
 }
 class my_drawer extends StatelessWidget {
   String email,name,profileimg,background;
my_drawer({this.background,this.profileimg,this.name,this.email});
   @override
   Widget build(BuildContext context) {
     return new ListView(
        children: <Widget>[
          new UserAccountsDrawerHeader(
            accountEmail: new Text(email),
            accountName: new Text(name),
            currentAccountPicture: new CircleAvatar(
              backgroundImage: new AssetImage(profileimg),
            ),
            decoration: new BoxDecoration(
              image: new DecorationImage(
                image: new AssetImage(background),
                fit: BoxFit.cover
              )
            ),
          ),
          new ListTile(
            title: new Text("Home"),
            trailing: new Icon(Icons.home),
            onTap: (){print("Home");},
          ),
           new ListTile(
            title: new Text("Notification"),
            trailing: new Icon(Icons.notifications),
            onTap: (){print("Notification");},
          ),
           new ListTile(
            title: new Text("Exit"),
            trailing: new Icon(Icons.exit_to_app),
            onTap: (){print("Exit");},
          )
        ],
      );
   }
 }

Run

Copy the code or download it in the link below, build and run.

Reference

Here are the reference links:

Number Link
1. Download Example
2. Follow code author

Example 5: Flutter Custom Drawer with matrix Diagonal Animation

The example 5 teaches us how to animate a custom drawer with an awesome diagonal matrix transformation animation. See the screenshot below:

Flutter Diagonal, Animated Drawer

Step 1: Create Project

Start by creating an empty Flutter project.

Step 2: Dependencies

Add the following dependencies:
`

dependencies:
  flutter:
    sdk: flutter
  cupertino_icons: ^1.0.0
  matrix4_transform: ^1.1.5
  google_fonts:

Step 3: Create Layers

Create three layers:

(a). FirstLayer.dart

import 'package:flutter/material.dart';
class FirstLayer extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(
      height: MediaQuery.of(context).size.height,
      width: MediaQuery.of(context).size.width,
      decoration: BoxDecoration(
          gradient:
              LinearGradient(colors: [Color(0xFF4c41a3), Color(0xFF1f186f)])),
    );
  }
}

(b). SecondLayer.dart

import 'package:flutter/material.dart';
import 'package:matrix4_transform/matrix4_transform.dart';
SecondLayerState secondLayerState;
class SecondLayer extends StatefulWidget {
  @override
  SecondLayerState createState() => SecondLayerState();
  // openTab() => createState().openTab();
}
class SecondLayerState extends State<SecondLayer> {
  double xoffSet = 0;
  double yoffSet = 0;
  double angle = 0;
  bool isOpen = false;
  @override
  Widget build(BuildContext context) {
    secondLayerState = this;
    return AnimatedContainer(
        transform: Matrix4Transform()
            .translate(x: xoffSet, y: yoffSet)
            .rotate(angle)
            .matrix4,
        duration: Duration(milliseconds: 550),
        decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(10), color: Color(0xFF4c41a3)),
        child: Column(
          children: [
            Row(
              children: [],
            )
          ],
        ));
  }
}

(d). FirstLayer.dart

import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
class ThirdLayer extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(
      height: MediaQuery.of(context).size.height,
      width: MediaQuery.of(context).size.width,
      color: Colors.transparent,
      child: Padding(
        padding: const EdgeInsets.only(left: 15.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Padding(
                padding: const EdgeInsets.only(top: 100.0),
                child: Container(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      FlutterLogo(
                        size: MediaQuery.of(context).size.width / 4,
                      ),
                      Row(
                        children: [
                          Text(
                            "FLUTTER",
                            style: TextStyle(
                                fontSize: 17,
                                color: Colors.white,
                                fontWeight: FontWeight.bold),
                          ),
                          Text(
                            "HOLIC",
                            style: TextStyle(
                                fontSize: 17,
                                color: Colors.blue[200],
                                fontWeight: FontWeight.bold),
                          )
                        ],
                      )
                    ],
                  ),
                )),
            Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  "Home Screen",
                  style: TextStyle(
                    color: Colors.white,
                  ),
                ),
                Padding(
                  padding: EdgeInsets.only(bottom: 20),
                ),
                Text(
                  "Screen 2",
                  style: TextStyle(
                    color: Colors.white,
                  ),
                ),
                Padding(
                  padding: EdgeInsets.only(bottom: 20),
                ),
                Divider(
                  color: Color(0xFF5950a0),
                  thickness: 2,
                ),
                Padding(
                  padding: EdgeInsets.only(bottom: 20),
                ),
                Text(
                  "About",
                  style: TextStyle(
                    color: Colors.white,
                  ),
                ),
                Padding(
                  padding: EdgeInsets.only(bottom: 20),
                ),
                Text(
                  "Share App",
                  style: TextStyle(
                    color: Colors.white,
                  ),
                ),
                Padding(
                  padding: EdgeInsets.only(bottom: 20),
                ),
                Divider(
                  color: Color(0xFF5950a0),
                  thickness: 2,
                ),
                Padding(
                  padding: EdgeInsets.only(bottom: 20),
                ),
                Text(
                  "Bye",
                  style: TextStyle(
                    color: Colors.white,
                  ),
                ),
                Padding(
                  padding: EdgeInsets.only(bottom: 10),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }
}

Step 4: Create custom Drawer

Create the custom drawer:

CustomDrawer.kt

import 'package:custom_drawer/FirstLayer.dart';
import 'package:custom_drawer/HomePage.dart';
import 'package:custom_drawer/SecondLayer.dart';
import 'package:custom_drawer/ThirdLayer.dart';
import 'package:flutter/material.dart';
class CustomDrawer extends StatefulWidget {
  @override
  _CustomDrawerState createState() => _CustomDrawerState();
}
class _CustomDrawerState extends State<CustomDrawer> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Stack(
        children: [
          FirstLayer(),
          SecondLayer(),
          ThirdLayer(),
          HomePage(),
        ],
      ),
    );
  }
}

Step 5: Create main class

main.dart

import 'package:custom_drawer/CustomDrawer.dart';
import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
void main() {
  runApp(CustomDrawerApp());
}
class CustomDrawerApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData(
          textTheme: GoogleFonts.solwayTextTheme(
        Theme.of(context).textTheme,
      )),
      home: CustomDrawer(),
    );
  }
}

Run

Copy the code or download it in the link below, build and run.

Reference

Here are the reference links:

Number Link
1. Download Example
2. Follow code author

Example 6: Flutter Grouped NavigationDrawer

What about if you want a NavigationDrawer, whereby menu items are grouped. There is also a header with image and text. The menu items also are made up of text and images.

Here is the demo:

Step 1: Create Project

Start by creating an empty Flutter project.

Step 2: Dependencies

No special dependencies are needed.

Step 3: Add assets

Add your images under the assets/icons folder then register the asset in the pubspec.yaml using the following line:

  assets:
   - assets/icons/ic_pic_male_placeholder.png

Step 4: Create Model classes

You need to create model classes:

user.dart

import 'package:flutter/material.dart';
class User {
  final name;
  final picUrl;
  User({this.name, this.picUrl});
}

Step 5: Create Screens

Create Screens:

help.dart

import 'package:flutter/material.dart';
class User {
  final name;
  final picUrl;
  User({this.name, this.picUrl});
}

about.dart

import 'package:flutter/material.dart';
class AboutScreen extends StatelessWidget {
  static const String routeName = "/about";
  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text("About"),
      ),
      body: new Container(
          child: new Center(
        child: new Text("About"),
      )),
    );
  }
}

bookings.dart

import 'package:flutter/material.dart';
class BookingsScreen extends StatelessWidget {
  static const String routeNameScheduled = "/bookings/scheduled";
  static const String routeNameCompleted = "/bookings/completed";
  final BookingType bookingType;
  BookingsScreen({@required this.bookingType})
      : assert(bookingType != null);
  @override
  Widget build(BuildContext context) {
    var title = getTitle(bookingType);
    return Scaffold(
      appBar: AppBar(
        title: Text(title),
      ),
      body: Center(
        child: Container(
          child: Text(title),
        ),
      ),
    );
  }
  String getTitle(BookingType bookingType) {
    switch (bookingType) {
      case BookingType.SCHEDULED:
        return "Scheduled Bookings";
      case BookingType.COMPLETED:
        return "Completed Bookings";
      default:
        return "Bookings";
    }
  }
}
enum BookingType { SCHEDULED, COMPLETED }

Step 6: Download Full code

Go ahead and download the full code below.

Run

Copy the code or download it in the link below, build and run.

Reference

Here are the reference links:

Number Link
1. Download Example
2. Follow code author

Leave a Reply