Flutter Drawer with State Management
Tags: flutter, dartlang, dart, mobileapp
Published: 2019-06-25 20:19:47

---
title: Flutter Drawer with State Management
published: true
description: A new Flutter project demonstrating a pattern for managing state between the drawers in the application and using one widget to represent the drawer across multiple application pages
tags: #flutter, #dartlang, #dart, #mobileapp
---


## Getting Started

- Install the Provider Package from [Dart Pub](https://pub.dev/) the package manager for the Dart programming language, containing reusable libraries & packages
- The Provider Package
  - A dependency injection system built with widgets for widgets. provider is mostly syntax sugar for InheritedWidget, to make common use-cases straightforward.
  - [Provider Package Documentation][1]
  
## What It Looks Like
<table border=0>
  <tr>
    <td><img src="https://thepracticaldev.s3.amazonaws.com/i/fyiv380h08jatqa4bs6c.png"></td>
    <td><img src="https://thepracticaldev.s3.amazonaws.com/i/ivfzk1b9lh4lwgc1cwwg.png"></td>
    <td><img src="https://thepracticaldev.s3.amazonaws.com/i/g653bxnn4ftrm13wn3ke.png"></td>
  </tr>  
  <tr style="text-align:'center'">
    <td style="padding:0px">Home Page</td>
    <td style="padding:0px"><p>Drawer Showing Active Home Page</p></td>
    <td style="padding:0px"><p>Drawer Showing Active Active Page</p></td>
  </tr>   
</table>

## Quick Overview of Code

Create a separate widget for the drawer and just use in anywhere you need to.

Manage the Drawer State using a [Provider][1] that will keep track of currently selected menu item
- [Flutter ChangeNotifier Documentation](https://api.flutter.dev/flutter/foundation/ChangeNotifier-class.html)
- [Flutter notifyListeners method Documentation](https://api.flutter.dev/flutter/foundation/ChangeNotifier/notifyListeners.html)

this class contains state information and the appropriate methods to modify the state. When state updates happen, the call to [`notifyListeners`](https://api.flutter.dev/flutter/foundation/ChangeNotifier/notifyListeners.html) is call to let the application know the the appropriate widgets need to be redrawn
```dart
class DrawerStateInfo with ChangeNotifier {
  int _currentDrawer = 0;
  int get getCurrentDrawer => _currentDrawer;

  void setCurrentDrawer(int drawer) {
    _currentDrawer = drawer;
    notifyListeners();
  }

  void increment() {
    notifyListeners();
  }
}
```
Adding State Management to the Widget tree; we are using the `MultiProvider` here for demonstration purposes of how you could potentially have multiple classes managing different aspects of the application state. Each one would be added to the `providers` array property.
- [Flutter MultiProvider Documentation](https://pub.dev/documentation/provider/latest/provider/MultiProvider-class.html)
```dart
class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      child: MaterialApp(
        title: 'Flutter Demo',
        theme: ThemeData(
          primarySwatch: Colors.teal,
        ),
        home: MyHomePage(title: 'Flutter Demo Home Page'),
      ),
      providers: <SingleChildCloneableWidget>[
        ChangeNotifierProvider<DrawerStateInfo>(
            builder: (_) => DrawerStateInfo()),
      ],
    );
  }
}
```


Creating The Drawer Widget for reuse in application. We are tracking the state to specify which item is the active item in the menu and then based on that we are updating the styling of the menu item's title

- [Flutter Drawer Widget Documentation](https://api.flutter.dev/flutter/material/Drawer-class.html)
```dart
class MyDrawer extends StatelessWidget {
  MyDrawer(this.currentPage);

  final String currentPage;

  @override
  Widget build(BuildContext context) {
    var currentDrawer = Provider.of<DrawerStateInfo>(context).getCurrentDrawer;
    return Drawer(
      child: ListView(
        children: <Widget>[
          ListTile(
            title: Text(
              "Home",
              style: currentDrawer == 0
                  ? TextStyle(fontWeight: FontWeight.bold)
                  : TextStyle(fontWeight: FontWeight.normal),
            ),
            trailing: Icon(Icons.arrow_forward),
            onTap: () {
              Navigator.of(context).pop();
              if (this.currentPage == "Home") return;

              Provider.of<DrawerStateInfo>(context).setCurrentDrawer(0);

              Navigator.of(context).pushReplacement(MaterialPageRoute(
                  builder: (BuildContext context) =>
                      MyHomePage(title: "Home")));
            },
          ),
          ListTile(
            title: Text(
              "About",
              style: currentDrawer == 1
                  ? TextStyle(fontWeight: FontWeight.bold)
                  : TextStyle(fontWeight: FontWeight.normal),
            ),
            trailing: Icon(Icons.arrow_forward),
            onTap: () {
              Navigator.of(context).pop();
              if (this.currentPage == "About") return;

              Provider.of<DrawerStateInfo>(context).setCurrentDrawer(1);

              Navigator.of(context).pushReplacement(MaterialPageRoute(
                  builder: (BuildContext context) => MyAboutPage()));
            },
          ),
        ],
      ),
    );
  }
}

```

Use of Drawer in one of your pages; when using the Drawer, we specify the name of the Drawer when creating the instance. This should probably be a constant or maybe even an object containing addition information but this works for the example.
```dart
class MyAboutPage extends StatefulWidget {
  @override
  _MyAboutPageState createState() => _MyAboutPageState();
}

class _MyAboutPageState extends State<MyAboutPage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('About Page'),
      ),
      drawer: MyDrawer("About"),
    );
  }
}
```


  [1]: https://pub.dev/packages/provider




{% github aaronksaunders/flutter_drawer_detail %}


A few resources to get you started if this is your first Flutter project:

- [Lab: Write your first Flutter app](https://flutter.io/docs/get-started/codelab)
- [Cookbook: Useful Flutter samples](https://flutter.io/docs/cookbook)

For help getting started with Flutter, view the 
[online documentation](https://flutter.io/docs), which offers tutorials, 
samples, guidance on mobile development, and a full API reference.