Flutter Navigation – Named Routes

This is the third article of a multi-part series where we will focus on how to navigate within a Flutter app.  In this article

If you are interested in reading this entire series, here are the links for you:

Creating the App

If you are not yet familiar with the basics of creating a flutter app, please see my first post in this series on flutter – From Zero to App with Flutter.

Note – for this post we’ll be using VS Code although other IDEs may be used.  Open up VS Code and from the command palette (CTRL+SHIFT+P) choose ‘Flutter:New Project’.  Enter a new project name and hit Enter.  VS Code will setup your new project, which we will be heavily modifying next…

The app consists of 3 pages: home, about, & contact.  We’ll build a simple Drawer to use for navigation and we’ll discover how to navigate to a page based on a name.  Before we begin let’s review how to navigate without a named route:

Navigator.push(
      context, new MaterialPageRoute(builder: (context) => new AboutPage()));

Named routes makes it a bit easier.  Here is how you might construct the same navigation to an about page using named routes:

Navigator.of(context).pushNamed('/about');

In order for named routes to work, there is some upfront configuration to do.  Basically you have to tell your app what it’s named routes are supposed to be and what page they correspond to. Here is the code for your main.dart file.  Notice lines 18-22? This is how you tell your application what routes it will have.  When the Navigator gets a call to navigate to one of these names, the corresponding Widget is created and pushed onto the Navigation stack.

import 'package:flutter/material.dart';
import 'home.dart';
import 'about.dart';
import 'contact.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 Nav Demo 3',
      theme: new ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: new MyHomePage(),
      routes: <String, WidgetBuilder>{
        '/home': (BuildContext context) => new MyHomePage(),
        '/about': (BuildContext context) => new AboutPage(),
        '/contact': (BuildContext context) => new ContactPage(),
      },
    );
  }
}

Now that we have the main.dart file created, lets create the actual pages of this app – home, about, & contact.  Here is the code for each of these:

home.dart

import 'package:flutter/material.dart';

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => new _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return new Scaffold(
        appBar: new AppBar(
          title: new Text("Navigation Demo"),
          backgroundColor: Colors.deepOrangeAccent,
        ),
        drawer: new Drawer(
          child: new ListView(
            children: <Widget>[
              new ListTile(
                title: new Text("WELCOME"),
              ),
              new Divider(),
              new ListTile(
                  title: new Text("About"),
                  trailing: new Icon(Icons.info),
                  onTap: () {
                    Navigator.of(context).pop();
                    Navigator.of(context).pushNamed('/about');
                  }),
              new ListTile(
                  title: new Text("Contact"),
                  trailing: new Icon(Icons.phone),
                  onTap: () {
                    Navigator.of(context).pop();
                    Navigator.of(context).pushNamed('/contact');
                  }),
            ],
          ),
        ),
        body: new Center(
          child: new Text("Home Page", style: new TextStyle(fontSize: 35.0)),
        ));
  }
}

Take note of the ListTile.onTap() events and their containing code.  In each of this we first call pop – which closes the Navigation drawer.  Next  we call pushNamed and pass in the name of the route we want to navigate to – either ‘/about’ or ‘/contact’.

about.dart

import 'package:flutter/material.dart';

class AboutPage extends StatefulWidget {
  @override
  _AboutPageState createState() => new _AboutPageState();
}

class _AboutPageState extends State<AboutPage> {
  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text('About'),
        backgroundColor: Colors.deepOrangeAccent,
      ),
      body: new Center(
        child: new Text("About Page", style: new TextStyle(fontSize: 35.0)),
      ),
    );
  }
}

contact.dart

import 'package:flutter/material.dart';

class ContactPage extends StatefulWidget {
  @override
  _ContactPageState createState() => new _ContactPageState();
}

class _ContactPageState extends State<ContactPage> {
  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text('Contact'),
        backgroundColor: Colors.deepOrangeAccent,
      ),
      body: new Center(
        child: new Text("Contact Page", style: new TextStyle(fontSize: 35.0)),
      ),
    );
  }
}

The full source code of this app can be found here.

Summary

In this article we looked at navigating by a route name and contrasted it against other methods.  Once the initial routing configuration is setup, it will make the rest of the navigation in your app much simpler to put together and maintain.

This concludes our series on navigation within Flutter. I hope you enjoyed this article and let me know if there are other topics you are interested in.

2 thoughts on “Flutter Navigation – Named Routes”

Leave a Reply

Your email address will not be published. Required fields are marked *