Navigation and routing
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'sNavigatorand thego_routerpackage 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 inAndroidManifest.xmlends up on a Flutter screen. WillPopScopeis deprecated in favour ofPopScope, 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, aTimer, anAnimationController) must release them inState.dispose(). A route can disappear throughpop,context.go, or aredirect, and in every casedispose()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_routeris 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
redirectis 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. PopScopeis a "are you sure?" sign on the top plate: it can stop the back gesture from removing it.- A
NavigatorObserveris 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.
| Concept | Navigator / Router API | go_router |
|---|---|---|
| API style | Imperative push/pop, or declarative Page list | Declarative routes list, navigate with context.go / context.push |
| Deep links | onGenerateRoute, or your own RouteInformationParser | URL path matching with :param segments |
| Auth guards | Check in onGenerateRoute or in your RouterDelegate | redirect callback on GoRouter or on a GoRoute |
| Nested navigation | A nested Navigator widget | ShellRoute, or StatefulShellRoute with StatefulShellBranch for tabs that keep their own stacks |
| Returning a result | Navigator.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 nearestNavigator. 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. UseNavigator.of(context, rootNavigator: true)for full-screen dialogs and routes.MaterialPageRouteuses the platform's default page transition from the theme'sPageTransitionsTheme(an Android-style transition on Android, the Cupertino slide on iOS).CupertinoPageRoutealways uses the iOS-style slide.WillPopScopeis deprecated. UsePopScopewithcanPopandonPopInvokedWithResult. On Android, opt in to predictive back withandroid:enableOnBackInvokedCallback="true"in the manifest and test on a recent Android version.go_routerneedsMaterialApp.router(routerConfig: router)instead ofMaterialApp(home: ...).context.go('/path')replaces the stack with the matched route and its parents, similar to Navigation Compose'snavigatewithpopUpTo.context.push('/path')adds to the stack.context.replace('/path')swaps the top page.- A top-level
redirectreceives(BuildContext context, GoRouterState state). Return a locationStringto redirect, ornullto continue. It runs on every navigation, including deep-link arrivals, and can be async. refreshListenable(for example aValueNotifieror aChangeNotifierthat holds auth state) makesGoRouterre-runredirectwhen it notifies. Without it, logging in or out does not move the user until the next navigation.- To confirm before leaving a route,
GoRoutehas anonExitcallback that returnstrueto allow leaving orfalseto stay. UnlikePopScope, it also runs whengo_routeritself removes the route. - Read path and query values from
state.pathParameters['id']andstate.uri.queryParameters. Older tutorials usestate.params, which was renamed in go_router 7. NavigatorObserver.didPush,didPop,didReplace, anddidRemovefire 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", theVIEWaction, theDEFAULTandBROWSABLEcategories, and a<data>scheme and host, plus a validassetlinks.jsonon your domain. If you use a third-party deep-link plugin instead, setflutter_deeplinking_enabledtofalse.
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()(frompackage:flutter/services.dart) asks Android to close the activity; it is how a blocked root back gesture can still exit after confirmation.- Because
orders/:idis nested under/, a cold-start deep link to/orders/42builds Home and then Order, so the back button returns to Home instead of closing the app. - The redirect keeps the original location in a
fromquery parameter. After login,refreshListenablere-runs the redirect and it sends the user to/orders/42instead of dropping the deep link. context.pushkeeps Home underneath;context.go('/orders/42')would give the same stack here because of the nesting, butgoalways rebuilds the stack from the route tree rather than adding to the current one.PopScopewithcanPop: falseblocks the system back gesture;onPopInvokedWithResultthen runs withdidPopset tofalse, 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
- Users tapping a notification that opened
/orders/42on a cold start always ended up on the home screen after logging in, not on the order. - The
redirectchecked 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.
- Auth state moved into a
ChangeNotifierthat 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 tofrom. An integration test launches the app with the deep link and asserts the order screen is shown.
- After users left a live-chat screen, the app kept receiving chat events, and the logs showed
setState() called after dispose()errors. - The
ChatScreenstate cancelled the subscription it created ininitState, but a second subscription was created later in a callback and stored in a local variable, sodispose()never saw it. - Leaving the screen through
context.gofrom a notification made the problem more frequent, because users left the screen in the middle of the reconnect callback.
- Every subscription is now stored in a field (or a list of subscriptions) owned by the
State, anddispose()cancels all of them. - The
cancel_subscriptionslint was enabled inanalysis_options.yamlto flag subscriptions that are never cancelled. - A
NavigatorObserverlogsdidPopanddidRemovein 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 throughgo_router. - Using WillPopScope in new code. It is deprecated because it cannot support Android's predictive back gesture. Use
PopScopewithcanPopandonPopInvokedWithResult. - 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
redirectcallback 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.gorebuilds the stack from the route tree. If a flat route is the target, the previous screen is gone and back exits the screen unexpectedly. Usecontext.pushwhen the user expects to come back, or nest routes sogobuilds the right parents. - Forgetting to cancel subscriptions and timers in dispose(). Whether a route leaves by
pop,go, orredirect,dispose()runs once. Anything not cancelled there keeps running and may callsetStateon 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
Exercise: Add a deep-link route with an auth guard (15 min)
-
In a Flutter project, run
flutter pub add go_router. -
Replace
MaterialApp(home: ...)withMaterialApp.router(routerConfig: router), whererouteris aGoRouterwith/login,/(aHomeScreen), andprofile/:userIdnested under/(aProfileScreenthat showsstate.pathParameters['userId']). -
Create
final isLoggedIn = ValueNotifier<bool>(false);, pass it asrefreshListenable, and add aredirect: if not logged in and not on/login, return/login?from=plus the original location; if logged in and on/login, return thefromvalue or/. -
In
HomeScreen, add a button that callscontext.push('/profile/7'). Wrap the screen in aPopScopewithcanPop: falseand anonPopInvokedWithResultthat printsdidPop. -
In
android/app/src/main/AndroidManifest.xml, add an intent filter inside theMainActivity<activity>with theVIEWaction, theDEFAULTandBROWSABLEcategories, and<data android:scheme="myapp" android:host="open" />. Test it withadb 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.