Sub topic 1
From Navigator.push to declared routes
Prerequisites
This chapter assumes you can do the following:
- Write Dart with null safety and read
asynccode. - Build screens from
StatelessWidgetandStatefulWidget. - Use
Navigator.pushandNavigator.popwith aMaterialPageRoute. - Expose app state with
ChangeNotifieror something similar.
No go_router knowledge is needed. This chapter explains why the package exists and how its model differs from what you already use. Later chapters cover the API in detail.
The imperative model you already know
Navigator.push is imperative navigation. You tell the framework to do something to the navigation stack, and the stack is the only record of where the user is.
import 'package:flutter/material.dart';
void main() => runApp(const MaterialApp(home: HomeScreen()));
class HomeScreen extends StatelessWidget {
const HomeScreen({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Home')),
body: Center(
child: ElevatedButton(
onPressed: () {
Navigator.of(context).push(
MaterialPageRoute<void>(
builder: (context) => const BookScreen(id: '42'),
),
);
},
child: const Text('Open book 42'),
),
),
);
}
}
class BookScreen extends StatelessWidget {
const BookScreen({super.key, required this.id});
final String id;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Book $id')),
body: const Center(child: Text('Details')),
);
}
}This works well for small apps. After the button press the stack holds two pages, HomeScreen and BookScreen. Nothing in the app has a name for that situation. The stack exists only as the result of the calls that built it.
Where the imperative model strains
Several common requirements are awkward to meet with pushes and pops:
- Web URLs. A browser address bar expects every screen to have an address such as
/books/42. A pushedMaterialPageRoutehas none, unless you add named routes and keep them consistent. - Deep links. A link from an email or notification must open the app on the book screen with
Homeunderneath it, so Back behaves sensibly. With pushes you would have to run the right sequence of calls at startup. - Guards. To keep signed-out users away from a screen, you must remember to check at every call site. Missing one call site leaves a hole.
- Restoring a location. If the stack is only a side effect of past calls, you can't easily serialize it and rebuild it.
The older routes: map and onGenerateRoute give you string names. They are still a table of one-off pushes. There is no model of how pages relate to each other, and the framework doesn't treat the location as the app's state.
The declarative idea
Declarative routing reverses the direction. You declare which locations exist and which screen each one shows. Navigating means saying "the app is now at this location." The router works out which pages the stack should contain.
This follows the same principle as Flutter widgets. Instead of mutating a list of pages, you describe the target and let the framework reconcile.
| Aspect | Imperative (`Navigator.push`) | Declarative (`go_router`) |
|---|---|---|
| Source of truth | The stack, built by past calls | The current location, a URL-style string |
| Typical call | `push(MaterialPageRoute(...))` | `context.go('/books/42')` |
| Screens known up front | No, built at the call site | Yes, in one route table |
| Deep links and web URLs | Manual work per screen | Resolved from the route table |
| Guards | Checked at each call site | One `redirect` function |
| Back stack | Whatever was pushed | Derived from the route tree |
What it looks like
This is the same two-screen app, declared with go_router. The package must be in your pubspec.yaml under dependencies, for example by running flutter pub add go_router. HomeScreen and BookScreen are the classes from the earlier example, but HomeScreen now calls context.go.
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
final GoRouter router = GoRouter(
routes: <RouteBase>[
GoRoute(
path: '/',
builder: (context, state) => const HomeScreen(),
routes: <RouteBase>[
GoRoute(
path: 'books/:id',
builder: (context, state) =>
BookScreen(id: state.pathParameters['id']!),
),
],
),
],
);
void main() => runApp(MaterialApp.router(routerConfig: router));
class HomeScreen extends StatelessWidget {
const HomeScreen({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Home')),
body: Center(
child: ElevatedButton(
onPressed: () => context.go('/books/42'),
child: const Text('Open book 42'),
),
),
);
}
}
class BookScreen extends StatelessWidget {
const BookScreen({super.key, required this.id});
final String id;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Book $id')),
body: const Center(child: Text('Details')),
);
}
}The route table has a root route / and a child route books/:id. The :id segment is a path parameter, which state.pathParameters exposes to the builder.
Pressing the button doesn't construct a page by hand. It requests the location /books/42. The router matches it to the child route, builds HomeScreen and BookScreen as a stack, and the app bar shows a Back button. The next chapters explain each piece. Here you only need to see that the location drives the stack.
How it works underneath
Flutter has a lower-level API often called Navigator 2.0. It consists of the Router widget and a few cooperating pieces:
- The platform reports a location, for example from the browser URL or a deep link. This is a
RouteInformationobject. - A
RouteInformationParserturns that location into your own configuration type. - A
RouterDelegateturns the configuration into a list ofPageobjects and builds aNavigatorfrom them. - When the app changes state, the delegate reports the new location back to the platform, so the address bar stays in sync.
Writing these pieces by hand takes a lot of boilerplate. go_router implements all of them. You supply routes, and MaterialApp.router receives the result through routerConfig.
Every entry point feeds the same location. This is the main benefit: one code path handles a button press, a push notification, and a typed URL.
Trade-offs and gotchas
Declarative routing is not free. Know these points before you migrate.
- You design URLs now. Every screen you can reach directly needs a path. Choose the paths deliberately, because on the web they are public, and users bookmark them.
- State must fit in the location or elsewhere. Anything the destination needs has to come from the path, the query string, or app state. Passing arbitrary objects is possible but has limits, covered in a later chapter.
- Two models can coexist, with care.
go_routerstill supports pushing, and it is built onNavigator. Mixing it with directNavigator.pushcalls is possible, but those pushed routes don't update the location, so the address bar and deep-link behavior won't reflect them. goandpushbehave differently.goreplaces the stack with the one for the target location.pushadds a page on top of the current stack. Choosing wrongly is the most common early mistake, and a later chapter covers it.- Small apps may not need it. For an app with three screens, no web target, and no deep links,
Navigator.pushis simpler. Pick the router when the requirements above apply.
Decision criteria
Consider go_router when at least one of these holds:
- The app runs on the web, or you want shareable, bookmarkable addresses.
- The app must open from deep links or notifications.
- Navigation depends on authentication or other global state.
- You want a persistent bottom navigation bar where each tab keeps its own stack.
Stay with plain Navigator when the flow is short, linear, and local, such as a modal confirmation or a short wizard inside one feature. The two approaches combine well. You can use the router for app-level locations and Navigator for dialogs and sheets.
Exercise
Your app has a book screen reached by Navigator.push. A marketing email links to a specific book, and the link must open the book screen with the home screen underneath it. Explain why this is hard with imperative pushes, and what the declarative approach changes.
Show answer
With imperative pushes, the stack exists only as the result of earlier calls, and the book screen has no address. To handle the link you would have to detect it at startup and manually run the right sequence of calls, such as pushing the book screen onto the home screen, and repeat that logic for every linkable screen. With declarative routing you declare a route such as /books/:id nested under /. The incoming link is a location, the router matches it against the route table, and it derives the stack of home plus book automatically. The same code path handles button presses, deep links, and browser URLs.
Exercise
In the declarative example, what is the source of truth for where the user is, and what does context.go('/books/42') do with it?
Show answer
The source of truth is the current location, a URL-style string. context.go('/books/42') asks the router to change the location to /books/42. The router matches it against the route table, rebuilds the page stack for that location (home, then the book screen), and the Navigator displays the result.