Skip to content
Tutorials Center
My learning

Topics

Lesson 27 of 73 ยท Navigation

Navigator and Routes

Learn Flutter navigation with Navigator: the route stack, push and pop, passing data to a screen, returning results, named routes and the pitfalls around context.

Most apps have more than one screen: a list and a detail page, a login and a home. In Flutter, a screen is just a widget, and moving between screens is managed by the Navigator. The Navigator keeps a stack of routes. Opening a screen puts a new route on top; going back removes the top one, like a stack of cards.

This lesson shows the imperative API (push, pop), how to pass data forward and send results back, how named routes work, and where beginners get into trouble. The next lesson, Declarative routing with go_router, builds on these ideas for larger apps and web URLs.

Real vs stand-in. The Dart code is real Flutter code and is read-only here. The live examples are JavaScript stand-ins of a navigation stack: they show what push, pop, pushReplacement and returning a result do to the stack.

A stack of screens

push Put a new screen on top.
pop Remove the top screen.
pushReplacement Swap the top screen.
pushAndRemoveUntil Clear history, like after login.
1 / 2

push and pop

MaterialApp creates a Navigator for you and shows home as the first route. To open another screen:

DART
class HomePage extends StatelessWidget {
  const HomePage({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Home')),
      body: Center(
        child: FilledButton(
          onPressed: () {
            Navigator.of(context).push(
              MaterialPageRoute<void>(builder: (context) => const SettingsPage()),
            );
          },
          child: const Text('Open settings'),
        ),
      ),
    );
  }
}

class SettingsPage extends StatelessWidget {
  const SettingsPage({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Settings')),   // back button appears by itself
      body: Center(
        child: TextButton(
          onPressed: () => Navigator.of(context).pop(),
          child: const Text('Go back'),
        ),
      ),
    );
  }
}

MaterialPageRoute wraps your screen with the platform's transition (a slide on iOS, a fade-and-lift on Android) and supports the system back gesture. Navigator.of(context) finds the nearest Navigator above context; that lookup works like the ones in BuildContext and InheritedWidget. Calling pop on the root route would leave nothing to show, so use Navigator.canPop(context) when unsure.

Other methods you will meet:

  • pushReplacement: replace the current route (the old screen cannot be returned to).
  • pushAndRemoveUntil(route, (r) => false): push and clear everything below. Use it after login or logout.
  • popUntil(ModalRoute.withName('/')): pop until a condition is true.
  • maybePop(): pop, but let the screen veto it (see PopScope below).

Stand-in: the route stack

JS push, pop and replace on a stack

Press Run (or Ctrl + Enter) to see the console output here.

No output.

After pushAndRemoveUntil with "keep nothing", only dashboard remains, so the back button has nowhere to go. That is exactly what you want after signing in.

Passing data to a screen

Screens are widgets, so pass data through the constructor. This is type-safe: the compiler checks you gave it everything.

DART
class Recipe {
  const Recipe({required this.id, required this.title});
  final int id;
  final String title;
}

class RecipePage extends StatelessWidget {
  const RecipePage({super.key, required this.recipe});

  final Recipe recipe;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text(recipe.title)),
      body: Center(child: Text('Recipe #${recipe.id}')),
    );
  }
}

// Opening it:
Navigator.of(context).push(
  MaterialPageRoute<void>(builder: (_) => RecipePage(recipe: recipe)),
);

Returning a result

push returns a Future that completes when the route is popped, with the value given to pop. This is how a picker screen answers its caller:

DART
Future<void> chooseColor(BuildContext context) async {
  final String? picked = await Navigator.of(context).push<String>(
    MaterialPageRoute(builder: (_) => const ColorPickerPage()),
  );
  if (picked == null) return;          // the user pressed back
  if (!context.mounted) return;        // the screen may be gone after await
  ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('You chose $picked')));
}

// Inside ColorPickerPage:
Navigator.of(context).pop('teal');

Two safeguards: the result is nullable (back button, swipe or system gesture all give null), and after any await you check context.mounted before using context. Dialogs from the Material tour use exactly the same mechanism, because a dialog is just another route.

JS A route that returns a result

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Both calls resolve the promise that push returned. In Dart you write the same thing as await Navigator.push(...).

Named routes

You can register routes by name in MaterialApp and open them with a string:

DART
MaterialApp(
  initialRoute: '/',
  routes: {
    '/': (context) => const HomePage(),
    '/settings': (context) => const SettingsPage(),
  },
  onGenerateRoute: (settings) {
    if (settings.name == '/recipe') {
      final recipe = settings.arguments as Recipe;
      return MaterialPageRoute(builder: (_) => RecipePage(recipe: recipe));
    }
    return null;
  },
)

// Using them:
Navigator.of(context).pushNamed('/settings');
Navigator.of(context).pushNamed('/recipe', arguments: recipe);

Named routes keep paths in one place, but arguments become Object? and need a cast, so you lose type safety. Flutter's own documentation now recommends a routing package such as go_router instead of named routes for apps that need deep links or web URLs. Still, you will see them in existing code, so it is worth knowing.

Intercepting the back button

To warn about unsaved changes, wrap the screen in PopScope:

DART
PopScope(
  canPop: !hasUnsavedChanges,
  onPopInvokedWithResult: (didPop, result) async {
    if (didPop) return;
    final leave = await confirmDiscard(context);   // a dialog returning bool?
    if (leave == true && context.mounted) Navigator.of(context).pop();
  },
  child: const EditorPage(),
)

When canPop is false, the back gesture does not close the screen; the callback runs instead and you decide.

Common mistakes

  • Using context after an await without if (!context.mounted) return;.
  • Looking up a Navigator that does not exist above the context, for example in initState or above MaterialApp. Call it from a callback below MaterialApp.
  • Forgetting a result can be null.
  • Pushing the same screen repeatedly on double taps; disable the button or use pushReplacement.
  • Putting data in globals instead of constructor arguments or app state (Lifting state up).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does Navigator maintain?

    push adds a route to the top of the stack and pop removes the top one.
  2. 2. After a successful login you want the user unable to go back to the login screen. Which call fits best?

    pushAndRemoveUntil with a condition that keeps nothing clears the history, so the back button exits instead of returning to login.
  3. 3. What type does await Navigator.push<String>(...) give you, and when is it null?

    The Future completes with whatever pop received. If the user backs out, there is no value, so it is null.
  4. 4. What is the type-safe way to pass data to a new screen?

    Constructor parameters are checked by the compiler. Named-route arguments are Object? and need casts.
  5. 5. Why check context.mounted after await Navigator.push(...)?

    A lot can happen while the pushed screen is open. If your widget is gone, its context must not be used.

Summary

  • The Navigator holds a stack of routes; push and pop change what is on top.
  • pushReplacement and pushAndRemoveUntil change history, for example after login.
  • Pass data forward with constructors; get data back from the Future that push returns, which may be null.
  • Named routes work but lose type safety; larger apps usually move to go_router.
  • Use PopScope to intercept back, and check context.mounted after every await.

Next: Declarative Routing with go_router