website icon indicating copy to clipboard operation
website copied to clipboard

Add Navigation to 'Add a Drawer' to a screen

Open dipernaa opened this issue 8 years ago • 5 comments

From URL: https://flutter.io/cookbook/design/drawer/

Are there any plans to extend this cookbook example to include navigation? Navigation from a drawer is an extremely popular design pattern and it is difficult to find any good documentation on how to implement this design pattern. I wouldn't mind doing this myself but I am one of the people looking for guidance on how to implement this pattern.

dipernaa avatar Oct 22 '18 14:10 dipernaa

For reference, I am looking to create a navigation drawer just like Gmail or Keep Notes

dipernaa avatar Oct 22 '18 15:10 dipernaa

Here is a sample project I created but I feel like it is incorrect. By doing it this way I feel like there is no navigation stack/history, which is important.

dipernaa avatar Oct 22 '18 17:10 dipernaa

Hey @dipernaa -- Apologies for the delay in responding. Overall, I think we could definitely add recipes for this.

Since it might take me a bit of time to write up a full recipe, I'll put some code here that should hopefully show the concepts a bit.

Overall, you'll want to work with the Route and LocalHistoryEntry. These will allow you to register "History" events that should be intercepted by the back button.

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  final appTitle = 'Drawer Demo';

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: appTitle,
      home: MyHomePage(title: appTitle),
    );
  }
}

class MyHomePage extends StatefulWidget {
  final String title;

  MyHomePage({Key key, this.title}) : super(key: key);

  @override
  MyHomePageState createState() {
    return new MyHomePageState();
  }
}

class MyHomePageState extends State<MyHomePage> {
  // Keep track of the page history internally! We'll start with "Contacts" and
  // add or remove pages to this list.
  final _pageHistory = [PageType.contacts];

  // Returns the correct body based on the selected page.
  Widget _pageToWidget(PageType page) {
    switch (page) {
      case PageType.events:
        return EventsPage();
      case PageType.contacts:
      default:
        return ContactsPage();
    }
  }

  void _pushPage(PageType page) {
    // Close the Drawer when someone selects a new Screen
    Navigator.pop(context);

    // If we're already on the Selected Page, do not navigate to it!
    if (_pageHistory.last == page) return;

    // Create a LocalHistoryEntry and add it to the current route. This
    // will allow us to run the `_popPage` function when someone taps on
    // the back button!
    final route = ModalRoute.of(context);
    final entry = LocalHistoryEntry(onRemove: _popPage);
    route.addLocalHistoryEntry(entry);

    // Finally, add the history entry to our own Stack! This will allow us
    // to manage the navigation history.
    setState(() {
      _pageHistory.add(page);
    });
  }
  
  // When someone taps on the Back Button, remove the last page from our list of pages!
  void _popPage() {
    setState(() {
      _pageHistory.removeLast();
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text(widget.title)),
      // Render the body using the last entry in the History!
      body: _pageToWidget(_pageHistory.last),
      drawer: Drawer(
        child: ListView(
          padding: EdgeInsets.zero,
          children: <Widget>[
            DrawerHeader(
              child: Text('Drawer Header'),
              decoration: BoxDecoration(
                color: Colors.blue,
              ),
            ),
            ListTile(
              title: Text('Contacts'),
              onTap: () {
                _pushPage(PageType.contacts);
              },
            ),
            ListTile(
              title: Text('Events'),
              onTap: () {
                _pushPage(PageType.events);
              },
            ),
          ],
        ),
      ),
    );
  }
}

enum PageType { contacts, events }

class ContactsPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Center(
      child: Text('Contacts'),
    );
  }
}

class EventsPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Center(
      child: Text('Events'),
    );
  }
}

brianegan avatar Nov 06 '18 11:11 brianegan

From playing around with what you have built above, it builds a navigation stack that can get out of hand. For example, if someone navigated back and forth between Contacts and Events the navigation stack would keep building and it would be annoying to use the back button. I have modified what you have provided me with an alternative solution. My solution is to only add to the navigation stack if the route has not been added to it already. If it has been added to it already, then pop the navigation stack until that page is the last item in the stack. This way if you go from Contacts to Events to Contacts the result navigation stack will just be [Contacts] instead of [Contacts, Events, Contacts]. I have provided my alternate solution below.

import 'package:flutter/material.dart';

void main() => runApp(new MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(title: 'Flutter Demo', theme: new ThemeData(primarySwatch: Colors.blue), home: MyHomePage());
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key}) : super(key: key);

  @override
  MyHomePageState createState() => new MyHomePageState();
}

class MyHomePageState extends State<MyHomePage> {
  // Keep track of the page history internally! We'll start with "Contact Us" and
  // add or remove pages to this list.
  final _pageHistory = [PageHistoryItem(PageType.contacts, null)];

  // Returns the correct body based on the selected page.
  Widget _pageToWidget(PageType page) {
    switch (page) {
      case PageType.about:
        return AboutPage();
      case PageType.events:
        return EventsPage();
      case PageType.contacts:
      default:
        return Contacts();
    }
  }

  void _pushPage(PageType page) {
    // Close the Drawer when someone selects a new Screen
    Navigator.pop(context);

    // If we're already on the Selected Page, do not navigate to it!
    if (_pageHistory.last.type == page) return;

    int pageIndex;
    bool containsPage = false;
    for (int i = 0; i < _pageHistory.length && containsPage == false; i += 1) {
      containsPage = _pageHistory[i].type == page;

      if (containsPage) {
        pageIndex = i;
      }
    }

    if (containsPage) {
      for (int i = _pageHistory.length - 1; i > pageIndex; i -= 1) {
        PageHistoryItem removedPage = _pageHistory.elementAt(i);
        if (removedPage.historyEntry != null) {
          ModalRoute.of(context).removeLocalHistoryEntry(removedPage.historyEntry);
        }
      }
    } else {
      // Finally, add the history entry to our own Stack! This will allow us
      // to manage the navigation history.
      setState(() {
        // Create a LocalHistoryEntry and add it to the current route. This
        // will allow us to run the `_popPage` function when someone taps on
        // the back button!
        final route = ModalRoute.of(context);
        final entry = LocalHistoryEntry(onRemove: _popPage);
        route.addLocalHistoryEntry(entry);

        _pageHistory.add(PageHistoryItem(page, entry));
      });
    }
  }

  // When someone taps on the Back Button, remove the last page from our list of pages!
  void _popPage() {
    setState(() {
      _pageHistory.removeLast();
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Drawer Navigation')),
      // Render the body using the last entry in the History!
      body: _pageToWidget(_pageHistory.last.type),
      drawer: Drawer(
        child: ListView(
          padding: EdgeInsets.zero,
          children: <Widget>[
            DrawerHeader(
              child: Text('Drawer Navigation'),
              decoration: BoxDecoration(
                color: Colors.blue,
              ),
            ),
            ListTile(title: Text('Contact Us'), onTap: () => _pushPage(PageType.contacts)),
            ListTile(title: Text('About'), onTap: () => _pushPage(PageType.about)),
            ListTile(title: Text('Events'), onTap: () => _pushPage(PageType.events)),
          ],
        ),
      ),
    );
  }
}

class PageHistoryItem {
  final PageType type;
  final LocalHistoryEntry historyEntry;

  PageHistoryItem(this.type, this.historyEntry);
}

enum PageType { about, contacts, events }

class EventsPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: new Text('eventing'),
    );
  }
}

class Contacts extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: new Text('contacting'),
    );
  }
}

class AboutPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: new Text('about us'),
    );
  }
}

dipernaa avatar Nov 06 '18 14:11 dipernaa

Let's see if I can help close this issue :)

I agree that having a Drawer example with navigation is a good idea. However, I think that is should work similarly to how bottom navigation bar works, which is similar to the implementation found here: https://api.flutter.dev/flutter/material/BottomNavigationBar-class.html

When the user selects an item in the Navigator Bar, or the Drawer, the "body" of the Scaffold changes to one of the Widgets defined. In the Bottom Navigation Bar example I link, it is using an array to define these.

This implementation is fairly simple and works, but has some limitations, for example if you want to keep different navigation stacks per item, or if you want to keep the widget state. There are ways to implement those, but it would be IMO out of scope for a cookbook recipe.

Finally, a better approach is using go_router and the so called ShellRoute, which allows for sub-navigation using things like tabs, navigation bars, and drawers. As well, this won't be possible to implement in a cookbook.

What I will do to approach this, is to modify the existing recipe in https://flutter.dev/cookbook/design/drawer/ and add navigation to it in the same way it is implemented in the example https://api.flutter.dev/flutter/material/BottomNavigationBar-class.html, but also talking about its limitations and linking to the go_router package as a more complete solution.

Any thoughts on this?

miquelbeltran avatar Jun 27 '23 13:06 miquelbeltran