Sub topic 3
Setting up go_router
This chapter assumes you know Dart async and await, basic widgets such as Scaffold and AppBar, what BuildContext is, and how to run a Flutter app. You should also be comfortable with Navigator.push and pop from the earlier chapters. Add the package with flutter pub add go_router.
Configuring the router
go_router describes each screen as a URL path. You create one GoRouter and pass it to MaterialApp.router.
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
final GoRouter router = GoRouter(
initialLocation: '/',
routes: [
GoRoute(
path: '/',
builder: (context, state) => const HomeScreen(),
routes: [
GoRoute(
path: 'products/:id',
builder: (context, state) =>
ProductScreen(id: state.pathParameters['id']!),
),
],
),
],
);
void main() => runApp(MaterialApp.router(routerConfig: router));
class HomeScreen extends StatelessWidget {
const HomeScreen({super.key});
@override
Widget build(BuildContext context) => Scaffold(
appBar: AppBar(title: const Text('Home')),
body: Center(
child: ElevatedButton(
onPressed: () => context.go('/products/42'),
child: const Text('Open product 42'),
),
),
);
}
class ProductScreen extends StatelessWidget {
const ProductScreen({super.key, required this.id});
final String id;
@override
Widget build(BuildContext context) => Scaffold(
appBar: AppBar(title: Text('Product $id')),
);
}context.go replaces the current location. context.push adds a screen to the stack, as Navigator.push does.
Path and query parameters
A path parameter, written as :name in the route path, is required. A query parameter follows ? in the URL and is optional.
| Kind | Example URL | Read with |
|---|---|---|
| Path | `/products/42` | `state.pathParameters['id']` |
| Query | `/products/42?ref=home` | `state.uri.queryParameters['ref']` |
Redirects and authentication guards
A redirect callback runs before a location is shown. It returns a new path to send the user elsewhere, or null to continue. refreshListenable re-runs the callback when the auth state changes.
class AuthNotifier extends ChangeNotifier {
bool isLoggedIn = false;
void signIn() {
isLoggedIn = true;
notifyListeners();
}
}
final AuthNotifier auth = AuthNotifier();
final GoRouter router = GoRouter(
initialLocation: '/',
refreshListenable: auth,
redirect: (context, state) {
final goingToLogin = state.matchedLocation == '/login';
if (!auth.isLoggedIn && !goingToLogin) return '/login';
if (auth.isLoggedIn && goingToLogin) return '/';
return null;
},
routes: [
GoRoute(path: '/', builder: (context, state) => const HomeScreen()),
GoRoute(
path: '/login',
builder: (context, state) => const Scaffold(body: Text('Log in')),
),
],
);Persistent bottom navigation with ShellRoute
A ShellRoute wraps its child routes in a shared widget, such as a bottom navigation bar. The child argument is the matched screen. Replace the router from the first section with this one.
class SearchScreen extends StatelessWidget {
const SearchScreen({super.key});
@override
Widget build(BuildContext context) =>
const Scaffold(body: Center(child: Text('Search')));
}
final GoRouter router = GoRouter(
initialLocation: '/home',
routes: [
ShellRoute(
builder: (context, state, child) => Scaffold(
body: child,
bottomNavigationBar: BottomNavigationBar(
currentIndex: state.matchedLocation == '/search' ? 1 : 0,
onTap: (i) => context.go(i == 0 ? '/home' : '/search'),
items: const [
BottomNavigationBarItem(icon: Icon(Icons.home), label: 'Home'),
BottomNavigationBarItem(icon: Icon(Icons.search), label: 'Search'),
],
),
),
routes: [
GoRoute(path: '/home', builder: (context, state) => const HomeScreen()),
GoRoute(
path: '/search',
builder: (context, state) => const SearchScreen(),
),
],
),
],
);Deep linking and URLs
A deep link is a URL that opens a specific screen in your app. go_router reads the incoming location, runs the same redirects, and shows the matching route. You still declare the URL schemes or domains in the Android and iOS project files.
Testing navigation in widget tests
Pump the app with MaterialApp.router, tap a control, and check the resulting screen.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:my_app/main.dart';
void main() {
testWidgets('tapping the button opens product 42', (tester) async {
await tester.pumpWidget(MaterialApp.router(routerConfig: router));
await tester.tap(find.text('Open product 42'));
await tester.pumpAndSettle();
expect(find.text('Product 42'), findsOneWidget);
});
}Replace my_app with your package name. pumpAndSettle waits for the page transition to finish before the assertion runs.
Exercise
Exercise
A logged-out user opens /products/42. Which path does the redirect return, and what happens if it returns null?
Show answer
The redirect returns '/login', so the user lands on the login screen. Returning null leaves the navigation unchanged, so the user sees /products/42.