A widget that manages a set of child widgets with a stack discipline.

Many apps have a navigator near the top of their widget hierarchy in order to display their logical history using an Overlay with the most recently visited pages visually on top of the older pages. Using this pattern lets the navigator visually transition from one page to another by moving the widgets around in the overlay. Similarly, the navigator can be used to show a dialog by positioning the dialog widget above the current page.

Using the Navigator

Mobile apps typically reveal their contents via full-screen elements called "screens" or "pages". In Flutter these elements are called routes and they're managed by a Navigator widget. The navigator manages a stack of Route objects and provides methods for managing the stack, like Navigator.push and Navigator.pop.

Displaying a full-screen route

Although you can create a navigator directly, it's most common to use the navigator created by a WidgetsApp or a MaterialApp widget. You can refer to that navigator with Navigator.of.

A MaterialApp is the simplest way to set things up. The MaterialApp's home becomes the route at the bottom of the Navigator's stack. It is what you see when the app is launched.

void main() {
  runApp(new MaterialApp(home: new MyAppHome()));
}

To push a new route on the stack you can create an instance of MaterialPageRoute with a builder function that creates whatever you want to appear on the screen. For example:

Navigator.of(context).push(new MaterialPageRoute<Null>(
  builder: (BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(title: new Text('My Page')),
      body: new Center(
        child: new FlatButton(
          child: new Text('POP'),
          onPressed: () {
            Navigator.of(context).pop();
          },
        ),
      ),
    );
  },
));

The route defines its widget with a builder function instead of a child widget because it will be built and rebuilt in different contexts depending on when it's pushed and popped.

As you can see, the new route can be popped, revealing the app's home page, with the Navigator's pop method:

Navigator.of(context).pop();

It usually isn't necessary to provide a widget that pops the Navigator in a route with a Scaffold because the Scaffold automatically adds a 'back' button to its AppBar. Pressing the back button causes Navigator.pop to be called. On Android, pressing the system back button does the same thing.

Using named navigator routes

Mobile apps often manage a large number of routes and it's often easiest to refer to them by name. The MaterialApp can be created with a Map<String, WidgetBuilder> which maps from a route's name to a builder function that will create it. The MaterialApp uses this map to create a value for its navigator's onGenerateRoute callback.

void main() {
  runApp(new MaterialApp(
    home: new MyAppHome(), // becomes the route named '/'
    routes: <String, WidgetBuilder> {
      '/a': (BuildContext context) => new MyPage(title: 'page A'),
      '/b': (BuildContext context) => new MyPage(title: 'page B'),
      '/c': (BuildContext context) => new MyPage(title: 'page C'),
    },
  ));
}

To show a route by name:

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

The app's home page route is named '/' by default and other routes are given pathnames by convention.

Routes can return a value

When a route is pushed to ask the user for a value, the value can be returned via the pop method's result parameter.

Methods that push a route return a Future. The Future resolves when the route is popped and the Future's value is the pop method's result parameter.

For example if we wanted to ask the user to press 'OK' to confirm an operation we could await the result of Navigator.push:

bool value = await Navigator.of(context).push(new MaterialPageRoute<bool>(
  builder: (BuildContext context) {
    return new Center(
      child: new GestureDetector(
        child: new Text('OK'),
        onTap: () { Navigator.of(context).pop(true); }
      ),
    );
  }
));

If the user presses 'OK' then value will be true. If the user backs out of the route, for example by pressing the Scaffold's back button, the value will be null.

When a route is used to return a value, the route's type parameter must match the type of pop's result. That's why we've used MaterialPageRoute<bool> instead of MaterialPageRoute<Null>.

Popup routes

Routes don't have to obscure the entire screen. PopupRoutes cover the screen with a barrierColor that can be only partially opaque to allow the current screen to show through. Popup routes are "modal" because they block input to the widgets below.

There are functions which create and show popup routes. For example: showDialog, showMenu, and showBottomSheet. These functions return their pushed route's Future as described above. Callers can await the returned value to take an action when the route is popped, or to discover the route's value.

There are also widgets which create popup routes, like PopupMenuButton and DropdownButton. These widgets create internal subclasses of PopupRoute and use the Naviagator's push and pop methods to show and dismiss them.

Custom routes

You can create your own subclass of one the widget library route classes like PopupRoute, ModalRoute, or PageRoute, to control the animated transition employed to show the route, the color and behavior of the route's modal barrier, and other aspects of the route.

The PageRouteBuilder class makes it possible to define a custom route in terms of callbacks. Here's an example that rotates and fades its child when the route appears or disappears. This route does not obscure the entire screen because it specifies opaque: false, just as a popup route does.

Navigator.of(context).push(new PageRouteBuilder(
  opaque: false,
  pageBuilder: (BuildContext context, _, __) {
    return new Center(child: new Text('My PageRoute'));
  },
  transitionsBuilder: (_, Animation<double> animation, __, Widget child) {
    return new FadeTransition(
      opacity: animation,
      child: new RotationTransition(
        turns: new Tween<double>(begin: 0.5, end: 1.0).animate(animation),
        child: child,
      ),
    );
  }
));

The page route is built in two parts, the "page" and the "transitions". The page becomes a descendant of the child passed to the buildTransitions method. Typically the page is only built once, because it doesn't depend on its animation parameters (elided with _ and __ in this example). The transition is built on every frame for its duration.

Inheritance

Constants

defaultRouteName String

The default name for the initial route.

'/'

Static Methods

canPop(BuildContext context) bool

Whether the navigator that most tightly encloses the given context can be popped.

maybePop(BuildContext context, [ result ]) Future<bool>

Returns the value of the current route's willPop method. This method is typically called before a user-initiated pop. For example on Android it's called by the binding for the system's back button.

of(BuildContext context) NavigatorState

The state from the closest instance of this class that encloses the given context.

pop(BuildContext context, [ result ]) bool

Pop a route off the navigator that most tightly encloses the given context.

popAndPushNamed(BuildContext context, String routeName, { result }) Future

Executes a simple transaction that both pops the current route off and pushes a named route into the navigator that most tightly encloses the given context.

popUntil(BuildContext context, RoutePredicate predicate) → void

Calls pop() repeatedly until the predicate returns true.

push(BuildContext context, Route route) Future

Adds the given route to the history of the navigator that most tightly encloses the given context, and transitions to it.

pushNamed(BuildContext context, String routeName) Future

Push a named route onto the navigator that most tightly encloses the given context.

pushReplacement(BuildContext context, Route route, { result }) Future

Replace the current route by pushing route and then disposing the current route.

pushReplacementNamed(BuildContext context, String routeName, { result }) Future

Replace the current route by pushing the route named routeName and then disposing the previous route.

Constructors

Creates a widget that maintains a stack-based history of child widgets.

Properties

initialRoute String

The name of the first route to show.

final
observers List<NavigatorObserver>

A list of observers for this navigator.

final
onGenerateRoute RouteFactory

Called to generate a route for a given RouteSettings.

final
onUnknownRoute RouteFactory

Called when onGenerateRoute fails to generate a route.

final
hashCode int

Get a hash code for this object.

read-only, inherited
key Key

Controls how one widget replaces another widget in the tree.

final, inherited
runtimeType Type

A representation of the runtime type of the object.

read-only, inherited

Operators

operator ==(other) bool

The equality operator.

inherited

Methods

createState() NavigatorState

Creates the mutable state for this widget at a given location in the tree.

createElement() StatefulElement

Creates a StatefulElement to manage this widget's location in the tree.

inherited
debugFillDescription(List<String> description) → void

Add additional information to the given description for use by toString.

mustCallSuper, protected, inherited
noSuchMethod(Invocation invocation) → dynamic

Invoked when a non-existent method or property is accessed.

inherited
toString() String

Returns a string representation of this object.

inherited
toStringShort() String

A short, textual description of this widget.

inherited