Navigation and routing

Learn Flutter navigation for Android developers: Navigator vs go_router, redirects for auth, Android deep links and App Links, and PopScope for back handling. About 25 minutes.

Why it matters

  • Every Flutter app with more than one screen needs a routing layer. Android developers already think in Navigation Compose (NavHost, routes, back stack); Flutter's Navigator and the go_router package fill the same role, and mixing their APIs carelessly causes subtle back-stack bugs.
  • Android deep links and App Links arrive as an Intent; Flutter turns the URI into a route location. If the routing layer does not match that path, the user lands on the wrong screen. Interviewers ask how an intent filter in AndroidManifest.xml ends up on a Flutter screen.
  • WillPopScope is deprecated in favour of PopScope, which was added to support Android's predictive back gesture. Knowing the replacement and why it changed is a quick interview signal.
  • Routes that hold resources (a StreamSubscription, a Timer, an AnimationController) must release them in State.dispose(). A route can disappear through pop, context.go, or a redirect, and in every case dispose() is the one place cleanup is guaranteed.

The simple explanation

  • A navigation stack is a pile of plates: you add a plate on top (push), remove the top plate (pop), or swap the top plate (replace).
  • go_router is like a train timetable: you declare every station (route) up front, and asking to "go" to a station gives you the matching path of stops.
  • A redirect is a security guard at the gate: before you enter a station, the guard checks your ticket (auth state) and may send you to a different station.
  • PopScope is a "are you sure?" sign on the top plate: it can stop the back gesture from removing it.
  • A NavigatorObserver is a security camera: it watches every push, pop, and replace without changing the flow.

How does navigation work in Flutter? A Navigator widget keeps a stack of Route objects, much like a back stack in Android's Navigation component. Flutter offers two APIs on top of it. The imperative one (often called Navigator 1.0) is Navigator.of(context).push(MaterialPageRoute(builder: ...)) and pop(). It is not deprecated and is fine for simple flows. The declarative Router API (often called Navigator 2.0) describes the stack as a list of Page objects built from app state, using a RouterDelegate and a RouteInformationParser; it is powerful but verbose. go_router is a package from the Flutter team, published on pub.dev, built on the Router API: you declare GoRoute entries with URL paths, and the router turns a location string such as /orders/42 into a stack of pages. It handles deep links, redirects, and nested navigation with far less code.

ConceptNavigator / Router APIgo_router
API styleImperative push/pop, or declarative Page listDeclarative routes list, navigate with context.go / context.push
Deep linksonGenerateRoute, or your own RouteInformationParserURL path matching with :param segments
Auth guardsCheck in onGenerateRoute or in your RouterDelegateredirect callback on GoRouter or on a GoRoute
Nested navigationA nested Navigator widgetShellRoute, or StatefulShellRoute with StatefulShellBranch for tabs that keep their own stacks
Returning a resultNavigator.pop(context, value)await context.push<T>(...) and context.pop(value)

The key mechanism: go_router listens to the current location and rebuilds the Navigator's list of pages. context.go('/orders/42') sets the location, so the stack becomes the matched route plus its parent routes (if /orders/:id is nested under /, you get Home then Order). context.push('/orders/42') adds the matched page on top of the existing stack. When a page leaves the stack for any reason, its widgets are unmounted and each State.dispose() runs.

PopScope replaces the deprecated WillPopScope. Set canPop: false to block a back gesture, and use onPopInvokedWithResult(didPop, result) to react (for example, show a confirmation dialog when didPop is false). The new API decides before the gesture starts whether a pop is allowed, which is what Android's predictive back animation needs.

For Android deep links, an intent filter on MainActivity (the activity that extends FlutterActivity) delivers the URI to the Flutter engine. Flutter's built-in deep-link handling (on by default in recent Flutter versions, controlled by the flutter_deeplinking_enabled manifest flag) passes the path to the router, and go_router matches it like any other location.

Notes

  • Navigator.of(context) walks up the widget tree to the nearest Navigator. From inside a nested navigator it returns the nested one, not the root. This is the most common source of "my push went to the wrong stack" bugs. Use Navigator.of(context, rootNavigator: true) for full-screen dialogs and routes.
  • MaterialPageRoute uses the platform's default page transition from the theme's PageTransitionsTheme (an Android-style transition on Android, the Cupertino slide on iOS). CupertinoPageRoute always uses the iOS-style slide.
  • WillPopScope is deprecated. Use PopScope with canPop and onPopInvokedWithResult. On Android, opt in to predictive back with android:enableOnBackInvokedCallback="true" in the manifest and test on a recent Android version.
  • go_router needs MaterialApp.router(routerConfig: router) instead of MaterialApp(home: ...).
  • context.go('/path') replaces the stack with the matched route and its parents, similar to Navigation Compose's navigate with popUpTo. context.push('/path') adds to the stack. context.replace('/path') swaps the top page.
  • A top-level redirect receives (BuildContext context, GoRouterState state). Return a location String to redirect, or null to continue. It runs on every navigation, including deep-link arrivals, and can be async.
  • refreshListenable (for example a ValueNotifier or a ChangeNotifier that holds auth state) makes GoRouter re-run redirect when it notifies. Without it, logging in or out does not move the user until the next navigation.
  • To confirm before leaving a route, GoRoute has an onExit callback that returns true to allow leaving or false to stay. Unlike PopScope, it also runs when go_router itself removes the route.
  • Read path and query values from state.pathParameters['id'] and state.uri.queryParameters. Older tutorials use state.params, which was renamed in go_router 7.
  • NavigatorObserver.didPush, didPop, didReplace, and didRemove fire for route changes. Use them for analytics screen tracking, and keep them cheap: they run on the UI isolate.
  • For Android App Links, the intent filter needs android:autoVerify="true", the VIEW action, the DEFAULT and BROWSABLE categories, and a <data> scheme and host, plus a valid assetlinks.json on your domain. If you use a third-party deep-link plugin instead, set flutter_deeplinking_enabled to false.

Code example

This shows a go_router configuration with a nested parameterised route, an auth redirect that remembers where the user was going, a refreshListenable so login re-runs the redirect, and a PopScope that asks before leaving the home screen.

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:go_router/go_router.dart';
 
// In a real app this lives in your state layer (Riverpod, Bloc, a ChangeNotifier).
final isLoggedIn = ValueNotifier<bool>(false);
 
final router = GoRouter(
  initialLocation: '/',
  refreshListenable: isLoggedIn, // re-run redirect when auth changes
  redirect: (context, state) {
    final goingToLogin = state.matchedLocation == '/login';
    if (!isLoggedIn.value && !goingToLogin) {
      // Remember the original target, for example a deep link.
      return Uri(path: '/login', queryParameters: {'from': state.uri.toString()})
          .toString();
    }
    if (isLoggedIn.value && goingToLogin) {
      return state.uri.queryParameters['from'] ?? '/';
    }
    return null; // no redirect
  },
  routes: [
    GoRoute(path: '/login', builder: (context, state) => const LoginScreen()),
    GoRoute(
      path: '/',
      builder: (context, state) => const HomeScreen(),
      routes: [
        // Nested: going to /orders/42 builds Home, then Order on top.
        GoRoute(
          path: 'orders/:id',
          builder: (context, state) =>
              OrderScreen(id: state.pathParameters['id']!),
        ),
      ],
    ),
  ],
);
 
void main() => runApp(MaterialApp.router(routerConfig: router));
 
class LoginScreen extends StatelessWidget {
  const LoginScreen({super.key});
 
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: ElevatedButton(
          onPressed: () => isLoggedIn.value = true, // redirect sends us on
          child: const Text('Log in'),
        ),
      ),
    );
  }
}
 
class HomeScreen extends StatelessWidget {
  const HomeScreen({super.key});
 
  @override
  Widget build(BuildContext context) {
    return PopScope(
      canPop: false,
      onPopInvokedWithResult: (didPop, result) async {
        if (didPop) return;
        final leave = await showDialog<bool>(
          context: context,
          builder: (context) => AlertDialog(
            title: const Text('Leave the app?'),
            actions: [
              TextButton(
                onPressed: () => Navigator.pop(context, false),
                child: const Text('Stay'),
              ),
              TextButton(
                onPressed: () => Navigator.pop(context, true),
                child: const Text('Leave'),
              ),
            ],
          ),
        );
        if (leave == true) {
          await SystemNavigator.pop(); // close the app on Android
        }
      },
      child: Scaffold(
        body: Center(
          child: ElevatedButton(
            onPressed: () => context.push('/orders/42'),
            child: const Text('Open order'),
          ),
        ),
      ),
    );
  }
}
 
class OrderScreen extends StatelessWidget {
  const OrderScreen({super.key, required this.id});
  final String id;
 
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Order $id')),
      body: Center(child: Text('Order $id')),
    );
  }
}
  • SystemNavigator.pop() (from package:flutter/services.dart) asks Android to close the activity; it is how a blocked root back gesture can still exit after confirmation.
  • Because orders/:id is nested under /, a cold-start deep link to /orders/42 builds Home and then Order, so the back button returns to Home instead of closing the app.
  • The redirect keeps the original location in a from query parameter. After login, refreshListenable re-runs the redirect and it sends the user to /orders/42 instead of dropping the deep link.
  • context.push keeps Home underneath; context.go('/orders/42') would give the same stack here because of the nesting, but go always rebuilds the stack from the route tree rather than adding to the current one.
  • PopScope with canPop: false blocks the system back gesture; onPopInvokedWithResult then runs with didPop set to false, which is where the dialog goes.

Run the idea in plain Kotlin

class NavStack {
  private val stack = ArrayDeque<String>()

  fun push(route: String) {
      stack.addLast(route)
      println("push " + route + " -> " + stack)
  }

  fun pop() {
      if (stack.size <= 1) {
          println("pop blocked at root -> " + stack)
          return
      }
      stack.removeLast()
      println("pop -> " + stack)
  }

  fun replace(route: String) {
      stack.removeLast()
      stack.addLast(route)
      println("replace " + route + " -> " + stack)
  }

  // Like context.go: the stack becomes the matched route plus its parents.
  fun go(location: String, parents: Map<String, String>) {
      val chain = ArrayDeque<String>()
      var current: String? = location
      while (current != null) {
          chain.addFirst(current)
          current = parents[current]
      }
      stack.clear()
      stack.addAll(chain)
      println("go " + location + " -> " + stack)
  }
}

fun main() {
  // Route tree: /orders/42 and /settings are nested under /
  val parents = mapOf("/orders/42" to "/", "/settings" to "/")
  val nav = NavStack()
  nav.push("/")
  nav.push("/orders/42")
  nav.push("/settings")
  nav.pop()
  nav.replace("/profile")
  nav.go("/orders/42", parents)
  nav.pop()
  nav.pop()
}

Expected output:

push / -> [/]
push /orders/42 -> [/, /orders/42]
push /settings -> [/, /orders/42, /settings]
pop -> [/, /orders/42]
replace /profile -> [/, /profile]
go /orders/42 -> [/, /orders/42]
pop -> [/]
pop blocked at root -> [/]

In production

Deep link lost behind the login redirect on cold start
  • Users tapping a notification that opened /orders/42 on a cold start always ended up on the home screen after logging in, not on the order.
  • The redirect checked an in-memory auth flag before the saved session had been restored from storage, so it saw "logged out" and returned /login.
  • The redirect returned a bare /login, so the original location was thrown away. After login the app went to / by default.
The fix
  • Auth state moved into a ChangeNotifier that starts in a "restoring" state; the redirect sends the user to a splash route while restoring instead of deciding too early.
  • The notifier was passed as refreshListenable, so the redirect re-runs when the session finishes loading or the user logs in.
  • The redirect now returns /login?from=<original location> and, once logged in, sends the user to from. An integration test launches the app with the deep link and asserts the order screen is shown.
Chat stream kept running after leaving the screen
  • After users left a live-chat screen, the app kept receiving chat events, and the logs showed setState() called after dispose() errors.
  • The ChatScreen state cancelled the subscription it created in initState, but a second subscription was created later in a callback and stored in a local variable, so dispose() never saw it.
  • Leaving the screen through context.go from a notification made the problem more frequent, because users left the screen in the middle of the reconnect callback.
The fix
  • Every subscription is now stored in a field (or a list of subscriptions) owned by the State, and dispose() cancels all of them.
  • The cancel_subscriptions lint was enabled in analysis_options.yaml to flag subscriptions that are never cancelled.
  • A NavigatorObserver logs didPop and didRemove in debug builds, which made it easy to check that the screen's state was disposed when expected.

Common mistakes

  • Calling Navigator.of(context) from below a nested Navigator and expecting the root. The call returns the nearest navigator, so the route is pushed onto the inner stack. Use Navigator.of(context, rootNavigator: true) when you mean the root, or navigate through go_router.
  • Using WillPopScope in new code. It is deprecated because it cannot support Android's predictive back gesture. Use PopScope with canPop and onPopInvokedWithResult.
  • Checking auth inside every route builder. This scatters auth logic across many files and is easy to miss on a new route. Put the check in the redirect callback so it runs once, centrally, on every navigation including deep links.
  • Forgetting refreshListenable. Without it, the redirect only re-runs on the next navigation, so logging out leaves the user on a protected screen. Pass your auth notifier as refreshListenable.
  • Using context.go where context.push is needed. context.go rebuilds the stack from the route tree. If a flat route is the target, the previous screen is gone and back exits the screen unexpectedly. Use context.push when the user expects to come back, or nest routes so go builds the right parents.
  • Forgetting to cancel subscriptions and timers in dispose(). Whether a route leaves by pop, go, or redirect, dispose() runs once. Anything not cancelled there keeps running and may call setState on a disposed widget.

Interview questions

Answer out loud first. Then reveal the answer and compare it at each depth.

“What is the difference between Navigator push/pop and go_router, and when would you choose one over the other?”

“How do you handle the Android back button in Flutter now that WillPopScope is deprecated?”

“A user taps a deep link to /orders/42 on a cold start and lands on the wrong screen. How do you debug this?”

“What happens to a StatefulWidget's State when go_router removes its route, and what can go wrong?”

Quiz

Which widget replaces the deprecated WillPopScope?

In go_router, the route /orders/:id is nested under /. What stack does context.go('/orders/42') produce?

A go_router redirect callback returns null. What happens?

You call Navigator.of(context) from a widget inside a nested Navigator. What does it return?

0 of 4 answered

Mini task

  1. In a Flutter project, run flutter pub add go_router.

  2. Replace MaterialApp(home: ...) with MaterialApp.router(routerConfig: router), where router is a GoRouter with /login, / (a HomeScreen), and profile/:userId nested under / (a ProfileScreen that shows state.pathParameters['userId']).

  3. Create final isLoggedIn = ValueNotifier<bool>(false);, pass it as refreshListenable, and add a redirect: if not logged in and not on /login, return /login?from= plus the original location; if logged in and on /login, return the from value or /.

  4. In HomeScreen, add a button that calls context.push('/profile/7'). Wrap the screen in a PopScope with canPop: false and an onPopInvokedWithResult that prints didPop.

  5. In android/app/src/main/AndroidManifest.xml, add an intent filter inside the MainActivity <activity> with the VIEW action, the DEFAULT and BROWSABLE categories, and <data android:scheme="myapp" android:host="open" />. Test it with adb shell am start -a android.intent.action.VIEW -d "myapp://open/profile/7".

Done condition: The button opens the profile screen showing 7. Pressing back on the home screen prints false. With the app closed, the adb command opens the login screen, and tapping log in lands on the profile for user 7 with Home underneath it.

Next: Platform channels