Flutter Beta

Learn cross-platform development with our collection of trusted high-quality Flutter tutorials!

Flutter Navigation: Getting Started

Learn about routes, navigation, and transitions for apps written using the Flutter cross-platform framework from Google.

4.8/5 16 Ratings

Version

  • Dart 2, Flutter 1.7, VS Code
Update note: Filip Babić updated this tutorial for Flutter 1.7 and Dart 2.4. The original tutorial was written by Joe Howard.

What’s better than an app with one screen? Why, an app with two screens, of course! :]

Navigation is a key part of the user experience for any mobile application. Due to the limited screen real estate on mobile devices, users will constantly be navigating between different screens. For example, from a list to a details screen, from a shopping cart to a checkout screen, from a menu into a form, and many other cases. Good navigation helps your users find their way around and get a sense of the breadth of your app.

The iOS navigation experience is often built-around a UINavigationController, which uses a stack-based approach to shifting between screens. On Android, the Activity stack is the central means to shift a user between different screens, although the use of Jetpack Navigation with a single-Activity architecture is a new and recommended approach. Unique transitions between screens in these stacks can help give your app a unique feel.

Just like the native SDKs, cross-platform development frameworks such as Flutter must provide a means for your app to switch between screens. In most cases, you’ll want the navigation approach to be consistent with what the users of each platform have come to expect – to have a native experience.

In this tutorial, you’ll see how Flutter implements navigation between the different screens of a cross-platform app, by learning about:

  • Routes and navigation
  • Popping off the stack
  • Returning a value from a route
  • Custom navigation transitions

If you’re new to Flutter, please check out our Getting Started with Flutter tutorial to see the basics of working with Flutter.

Getting Started

You can download the starter project for this tutorial from the Download Materials button at the top or bottom of the page.

This tutorial will be using VS Code, with the Flutter extension. You can also use IntelliJ IDEA or Android Studio, or work with a text editor of your choice with Flutter at the command line.

Open the starter project in VS Code by choosing File ▸ Open and finding the root folder of the starter project zip file:

Open starter project

VS Code will prompt you to fetch the packages you need for the project, so go ahead and do so:

Fetch packages

Once the project is open in VS Code, hit F5 to build and run the starter project. If VS Code prompts you to choose an environment to run the app in, choose “Dart & Flutter”:

Choose environment

Here is the project running in the iOS Simulator:

Starter in iOS Simulator

And here it is running on an Android emulator:

Starter in Android emulator

The “debug” banner you see is due to the fact that you’re running a debug build of the app, pretty neat!

The starter app shows the list of members in a GitHub organization. In this tutorial, you’ll navigate from this first screen to a new screen for each member.

Creating a Widget to Navigate To

You first need to create a screen to navigate to each member’s details. Elements of a Flutter UI take the form of UI widgets, so you’ll have to create a member widget.

First, right-click on the lib folder in the project, choose New File. Then create a new file named memberwidget.dart:

New File

Add import statements and a StatefulWidget subclass with the name MemberWidget to the new file:

import 'package:flutter/material.dart';

import 'member.dart';

class MemberWidget extends StatefulWidget {
  // 1
  final Member member;

  MemberWidget(this.member) {
    // 2
    if (member == null) {
      throw ArgumentError(
        "member of MemberWidget cannot be null. Received: '$member'");
    }
  }

  // 3
  @override
  createState() => MemberState(member);
}

Here you:

  1. Add a Member property for the widget.
  2. Make sure that the member argument is not-null in the widget constructor.
  3. Use a MemberState class for the state, passing along a Member object to the MemberState.

Add the MemberState class above MemberWidget in the same file:

class MemberState extends State<MemberWidget> {
  final Member member;

  MemberState(this.member);
}

Here, you’ve given MemberState a Member property and a constructor.

Each widget must override the build() method, so add the override to MemberState now:

@override
Widget build(BuildContext context) {
  return Scaffold(
      appBar: AppBar(
        title: Text(member.login),
      ),
      body: Padding(
          padding: EdgeInsets.all(16.0),
          child: Image.network(member.avatarUrl)));
}

You’re creating a Scaffold, a material design container, which holds an AppBar and a Padding with a child Image for the member avatar.

With the member screen all set up, you now have somewhere to navigate to! :]

Navigation using Routes

Navigation in Flutter is centered around the idea of routes.

Routes are similar in concept to the routes that you would use in a REST API, where each route is relative to some root. The widget main() acts like the root in your app (“/”) and all other routes are relative to that one.

One way to use routes is with PageRoute. Since you’re working with a Flutter MaterialApp, you’ll use the MaterialPageRoute.

Add an import to the top of ghflutterwidget.dart to pull in the member widget:

import 'memberwidget.dart';

Next, add a private method _pushMember() to GHFlutterState in the same file:

_pushMember(Member member) {
  Navigator.push(context,
      MaterialPageRoute(builder: (context) => MemberWidget(member)));
}

Here, you’re using Navigator to push a new MaterialPageRoute onto the stack, and you build the MaterialPageRoute using a MemberWidget.

Now you need to call _pushMember() when a user taps on a row in the list of members. You can do so by updating _buildRow() in GHFlutterState and adding an onTap attribute to the ListTile:

Widget _buildRow(int i) {
  return Padding(
    padding: const EdgeInsets.all(16.0),
    child: ListTile(
      title: Text("${_members[i].login}", style: _biggerFont),
      leading: CircleAvatar(
          backgroundColor: Colors.green,
          backgroundImage: NetworkImage(_members[i].avatarUrl)
      ),
      // Add onTap here:
      onTap: () { 
        _pushMember(_members[i]); 
      },
    )
  );
}

Now, when a row is tapped, your new method, _pushMember(), is called with the member that was tapped. This in turn will open up the details screen.

Hit F5 to build and run the app. Tap a member row and you should see the member detail screen come up:

Android emulator Details screen

And here’s the member screen running on iOS:

iOS Simulator Details screen

Notice that the back button on Android has the Android style and the back button on iOS has the iOS style. And also notice that the transition style when switching to the new screen matches the platform’s transition style.

Tapping the back button takes you back to the member list, but what if you want to manually trigger going back from your own button in the app?

Take me back

Popping the Stack

Since navigation in the Flutter app is working like a stack of widgets, and you’ve pushed a new screen widget onto the stack, you’ll pop from the stack in order to go back.

Inside memberwidget.dart, add an IconButton to MemberState by updating build() to add a Column in place of just the Image:

@override
Widget build(BuildContext context) {
  return Scaffold(
    appBar: AppBar(
      title: Text(member.login),
    ),
    body: Padding(
      padding: EdgeInsets.all(16.0),
      // Make child a Column here and add the IconButton
      child: Column(
        children: [
          Image.network(member.avatarUrl),
          IconButton(
            icon: Icon(Icons.arrow_back, color: Colors.green, size: 48.0),
            onPressed: () {
              Navigator.pop(context);
            })
        ])));
}

You’ve added the Column in order to layout the Image and an IconButton vertically. For the IconButton, you’ve set its onPressed value to call Navigator and pop the stack.

Build and run the app using F5, and you’ll be able to go back to the member list by tapping your new back arrow:


Adding back arrow

Returning a Value

Routes can return values. To see an example, add the following private async method to MemberState:

_showOKScreen(BuildContext context) async {
  // 1, 2
  bool value = await Navigator.push(context,
      MaterialPageRoute<bool>(builder: (BuildContext context) {
    return Padding(
        padding: const EdgeInsets.all(32.0),
        // 3
        child: Column(children: [
          GestureDetector(
              child: Text('OK'),
              // 4, 5
              onTap: () {
                Navigator.pop(context, true);
              }),
          GestureDetector(
              child: Text('NOT OK'),
              // 4, 5
              onTap: () {
                Navigator.pop(context, false);
              })
        ]));
  }));
  // 6
  var alert = AlertDialog(
    content: Text((value != null && value)
        ? "OK was pressed"
        : "NOT OK or BACK was pressed"),
    actions: <Widget>[
      FlatButton(
          child: Text('OK'),
          // 7
          onPressed: () {
            Navigator.pop(context);
          })
    ],
  );
  // 8
  showDialog(context: context, child: alert);
}

Here is what’s going on in this method:

  1. You push a new MaterialPageRoute onto the stack, this time with a type parameter of bool. The type parameter denotes the type you want to return when going back.
  2. You use await when pushing the new route, which waits until the route is popped.
  3. The route you push onto the stack has a Column that shows two text widgets with gesture detectors.
  4. Tapping on the text widgets causes calls to Navigator to pop the new route off the stack.
  5. In the calls to pop(), you pass a return value of true if the user tapped the “OK” text on the screen, and false if the user tapped “NOT OK”. If the user presses the back button instead, the value returned is null.
  6. You then create an AlertDialog to show the result returned from the route.
  7. Note that the AlertDialog itself must be popped off the stack.
  8. You call showDialog() to show the alert.

The primary points to note in the above are:

  1. The bool type parameter in MaterialPageRoute, which you can replace with any other type you want coming back from the route
  2. The fact that you pass the result back in the call to pop, for example, Navigator.pop(context, true).

Next, inside MemberState‘s build(), add a RaisedButton that calls _showOKScreen() as another child of the Column you added earlier:

@override
Widget build(BuildContext context) {
  return Scaffold(
      appBar: AppBar(
        title: Text(member.login),
      ),
      body: Padding(
          padding: EdgeInsets.all(16.0),
          child: Column(children: [
            Image.network(member.avatarUrl),
            IconButton(
                icon: Icon(Icons.arrow_back, color: Colors.green, size: 48.0),
                onPressed: () {
                  Navigator.pop(context);
                }),
            // Add this raised button
            RaisedButton(
                child: Text('PRESS ME'),
                onPressed: () {
                  _showOKScreen(context);
                })
          ])));
}

The RaisedButton you’ve added shows the new screen.

Hit F5 to build and run the app, tap the “PRESS ME” button, and then tap either “OK”, “NOT OK”, or the back button. You’ll get a result back from the new screen showing which of the results the user tapped:

Returning results

Creating Custom Transitions

In order to give the navigation of your app a unique feel, you can create a custom transition. One way to do so is to use a class like PageRouteBuilder that defines custom routes with callbacks.

Replace _pushMember() in GHFlutterState, with the following code, so that it pushes a new PageRouteBuilder onto the stack:

_pushMember(Member member) {
  // 1
  Navigator.push(
      context,
      PageRouteBuilder(
          opaque: true,
          // 2
          transitionDuration: const Duration(milliseconds: 1000),
          // 3
          pageBuilder: (BuildContext context, _, __) {
            return MemberWidget(member);
          },
          // 4
          transitionsBuilder:
              (_, Animation<double> animation, __, Widget child) {
            return FadeTransition(
              opacity: animation,
              child: RotationTransition(
                turns: Tween<double>(begin: 0.0, end: 1.0).animate(animation),
                child: child,
              ),
            );
          }));
}

Here you:

  1. Push a new PageRouteBuilder onto the stack.
  2. Specify the duration using transitionDuration.
  3. Create the MemberWidget screen using pageBuilder.
  4. Use the transitionsBuilder to create fade and rotation transitions when showing the new route.

Hit F5 to build and run the app, and see your new transition in action:

Custom Transition animation

Wow! That’s making me a little dizzy! :]

Where to Go From Here?

You can download the completed project using the Download Materials button at the top or bottom of the page.

This tutorial has just scratched the surface of navigation on Flutter. In future tutorials, we’ll dig even deeper, including looking more at modal navigation.

You can learn more about Flutter navigation by visiting:

As you’re reading the docs, check out in particular how to make named routes, which you call on a Navigator using pushNamed().

Stay tuned for more Flutter tutorials and screencasts on our Flutter page!

Feel free to share your feedback, findings or ask any questions in the comments below or in the forums. I hoped you enjoyed learning about navigation with Flutter!

Average Rating

4.8/5

Add a rating for this content

16 ratings

Contributors

Comments