Sub topic 1
From Navigator.push to declared routes
Prerequisites
This chapter assumes you know Dart null safety and async code, can build screens with StatelessWidget, and have used Navigator.push and Navigator.pop. Add the go_router package to your pubspec.yaml before you start.
Imperative navigation and declared routes
With Navigator.push, your code lists each step: push this page, push another, pop back. The stack of screens exists only as a history of calls. With go_router, you declare a table of routes, each tied to a URL-style path such as /books/42. Your code then requests a location, and the router builds the matching stack. Because each screen has a location, web URLs and deep links can reach it directly.
Setting up GoRouter with MaterialApp.router
A GoRouter holds your route table. Pass it to MaterialApp.router through routerConfig.
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
final GoRouter router = GoRouter(
initialLocation: '/',
routes: <RouteBase>[
GoRoute(
path: '/',
builder: (context, state) =>
const Scaffold(body: Center(child: Text('Home'))),
),
GoRoute(
path: '/books/:id',
builder: (context, state) => Scaffold(
body: Center(child: Text('Book ${state.pathParameters['id']}')),
),
),
],
);
void main() => runApp(MaterialApp.router(routerConfig: router));Defining routes and paths
Each GoRoute pairs a path with a builder. A segment that starts with a colon, such as :id, is a path parameter. The router matches it to any value and exposes it through state.pathParameters.
Navigating: go, push and pop
context.go('/books/42')replaces the stack with the stack for that location.context.push('/books/42')places the page on top of the current stack, so the back button returns to where you were.context.pop()removes the top page. Callcontext.canPop()first if the page might be the only one.
Path and query parameters
Path parameters identify a resource, as the :id segment does. Query parameters add optional values after a ?. Read them from state.uri.queryParameters.
GoRoute(
path: '/books/:id',
builder: (context, state) {
final String id = state.pathParameters['id']!;
final String? ref = state.uri.queryParameters['ref'];
return Scaffold(body: Center(child: Text('Book $id from ${ref ?? 'unknown'}')));
},
),Navigate with context.go('/books/42?ref=home') to show "Book 42 from home".
Exercise
You are on the home page and want the book page to open on top of it, so the back button returns home. Which call do you use, and why not go?
Show answer
Use context.push('/books/42'). Push adds the book page on top of the current stack. Go replaces the stack with the book location, so no page remains underneath for the back button to return to.