Mobile development · Intermediate · 22 min
Navigate between Flutter screens with go_router
By Padding · Updated 18 Nov 2026
Ubuntu 26.04 · Flutter 3.50.1 · Dart 3.14.0 · go_router 18.1
You will build a small Flutter reading-list app whose screens are reached by URL through go_router 18.1, with path parameters, bottom tabs that keep their own history, a sign-in redirect, correct Android back behaviour and deep-link configuration, all proved by widget tests.
On this page
Flutter's built-in Navigator lets you push and pop screens, but it has no idea what a URL is. Once an app needs links from a text message, a browser address bar, or a notification to open a particular screen, you want every screen to have an address. go_router, the routing package maintained by the Flutter team, gives you that: you describe your screens as a tree of paths such as /books/2, and the router builds the right stack of screens for whatever address arrives.
In this tutorial you build Shelf, a three-book reading-list app with a Books tab and an Account tab. Along the way you use path parameters, a StatefulShellRoute so each tab keeps its own history, a redirect that sends signed-out readers to a sign-in screen and back again, and the Android back button. You finish with the files that let https:// links open the app on Android and iOS. Every behaviour is checked by a widget test that runs without a device, so you can trust each piece before you try it on a phone.
Step 1 · Create the project and add go_router
Check your Flutter version first. This tutorial uses Flutter 3.50 and go_router 18.1, which needs Flutter 3.44 or later:
flutter --versionCreate an empty project in a throwaway folder and add go_router. The ^18.1.0 constraint accepts bug-fix and feature releases of 18 but not a future 19, which may change the API:
mkdir -p ~/go-router-demo
cd ~/go-router-demo
flutter create --empty --project-name shelf_app shelf_app
cd shelf_app
flutter pub add 'go_router:^18.1.0'Flutter 3.50 moved the Material widgets into their own package, material_ui, and flutter create already lists it in pubspec.yaml. Your files import package:material_ui/material_ui.dart. The older package:flutter/material.dart still works but is deprecated, and flutter analyze warns about it.
Check it worked
cd ~/go-router-demo/shelf_app
grep -E '^ (go_router|material_ui):' pubspec.yamlYou should see two lines, something like go_router: ^18.1.4 and material_ui: ^1.1.0.
Step 2 · Add the data and the sign-in state
The app needs two plain Dart pieces before any screens: a list of books and an object that knows whether the reader is signed in. Keep them separate from the widgets so the router and the tests can use them directly.
Run this from ~/go-router-demo/shelf_app to create lib/books.dart:
cd ~/go-router-demo/shelf_app
cat > lib/books.dart <<'EOF'
class Book {
const Book({required this.id, required this.title, required this.author});
final String id;
final String title;
final String author;
}
const books = <Book>[
Book(id: '1', title: 'Things Fall Apart', author: 'Chinua Achebe'),
Book(id: '2', title: 'Americanah', author: 'Chimamanda Ngozi Adichie'),
Book(id: '3', title: 'Weep Not, Child', author: "Ngũgĩ wa Thiong'o"),
];
/// Returns the book with [id], or null when no book has that ID.
Book? findBook(String id) => books.where((book) => book.id == id).firstOrNull;
EOFThen create lib/auth.dart. AuthState extends ChangeNotifier, so anything listening to it, including the router later on, hears about every sign-in and sign-out:
cd ~/go-router-demo/shelf_app
cat > lib/auth.dart <<'EOF'
import 'package:flutter/foundation.dart';
/// Whether the reader is signed in. A real app would also hold a token here,
/// kept in secure storage rather than in memory.
class AuthState extends ChangeNotifier {
bool _signedIn = false;
bool get signedIn => _signedIn;
void signIn() {
_signedIn = true;
notifyListeners();
}
void signOut() {
_signedIn = false;
notifyListeners();
}
}
EOFThe third author's name has two letters with tildes. It is there on purpose. Text from links, APIs and readers in many languages flows through your screens, and it is better to see it render in your own app now than in a bug report later.
Check it worked
cd ~/go-router-demo/shelf_app
flutter analyze lib/books.dart lib/auth.dartThe analyser should end with No issues found!.
Step 3 · Build the screens
Next come the screens: a book list, a book detail page, an account page, a sign-in page, a page for addresses that do not exist, and the shell that draws the bottom navigation bar around the two tabs.
Notice what BookScreen takes: a book ID, not a Book. That choice matters for deep links, and the next step but one explains why.
cd ~/go-router-demo/shelf_app
cat > lib/screens.dart <<'EOF'
import 'package:go_router/go_router.dart';
import 'package:material_ui/material_ui.dart';
import 'books.dart';
/// Draws the bottom navigation bar around whichever tab is active.
class AppShell extends StatelessWidget {
const AppShell({super.key, required this.navigationShell});
final StatefulNavigationShell navigationShell;
@override
Widget build(BuildContext context) {
return Scaffold(
body: navigationShell,
bottomNavigationBar: NavigationBar(
selectedIndex: navigationShell.currentIndex,
// Tapping the tab you are already on takes you back to its first screen.
onDestinationSelected: (index) => navigationShell.goBranch(
index,
initialLocation: index == navigationShell.currentIndex,
),
destinations: const [
NavigationDestination(icon: Icon(Icons.menu_book), label: 'Books'),
NavigationDestination(icon: Icon(Icons.person), label: 'Account'),
],
),
);
}
}
class BooksScreen extends StatelessWidget {
const BooksScreen({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Library')),
body: ListView(
children: [
for (final book in books)
ListTile(
title: Text(book.title),
subtitle: Text(book.author),
onTap: () => context.go('/books/${book.id}'),
),
],
),
);
}
}
class BookScreen extends StatelessWidget {
const BookScreen({super.key, required this.id});
final String id;
@override
Widget build(BuildContext context) {
final book = findBook(id);
return Scaffold(
appBar: AppBar(title: Text(book?.title ?? 'Book not found')),
body: Padding(
padding: const EdgeInsets.all(16),
child: Text(
book == null ? 'No book has the ID $id.' : 'By ${book.author}',
),
),
);
}
}
class AccountScreen extends StatelessWidget {
const AccountScreen({super.key, required this.onSignOut});
final VoidCallback onSignOut;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Your account')),
body: Center(
child: FilledButton(onPressed: onSignOut, child: const Text('Sign out')),
),
);
}
}
class SignInScreen extends StatelessWidget {
const SignInScreen({super.key, required this.onSignIn});
final VoidCallback onSignIn;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Sign in')),
body: Center(
child: FilledButton(
onPressed: onSignIn,
child: const Text('Continue as guest'),
),
),
);
}
}
class NotFoundScreen extends StatelessWidget {
const NotFoundScreen({super.key, required this.location});
final String location;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Page not found')),
body: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Text('Nothing lives at $location.'),
const SizedBox(height: 16),
FilledButton(
onPressed: () => context.go('/books'),
child: const Text('Go to books'),
),
],
),
),
);
}
}
EOFThree details are worth reading closely:
context.go('/books/2')tells the router where to be, and the router works out the stack: the book list with the book on top.context.push('/books/2')would instead place the book on top of whatever is showing now. Usegofor moving through your app's structure, andpushfor a screen that should return to wherever it was opened from, such as a picker that hands back a result.- The sign-in and account screens do not navigate when you press their buttons. They only change the sign-in state. The router reacts to that change, as you will see in the redirect step.
goBranchswitches tabs. PassinginitialLocation: truewhen the reader taps the tab they are already on resets that tab to its first screen, which is what most people expect from a bottom bar.
Check it worked
cd ~/go-router-demo/shelf_app
flutter analyze lib/screens.dartYou should see No issues found!. If the analyser cannot find StatefulNavigationShell, the go_router line is missing from pubspec.yaml; run flutter pub add 'go_router:^18.1.0' again.
Step 4 · Decide who may see which screen
A redirect is a function the router calls before it shows any address. It returns null to let the reader through, or another address to send them there instead. Writing it as a plain function, apart from the router, lets you test every case in milliseconds.
Shelf's rules:
- A signed-out reader who asks for any screen other than sign-in goes to
/sign-in, and the address they wanted is kept in afromquery parameter, such as/sign-in?from=%2Fbooks%2F2. - A signed-in reader on the sign-in screen goes to the
fromaddress, or to/bookswhen there is none. - Everyone else goes where they asked.
The from value arrives inside a link, so anyone can write it. Accept it only when it is a path inside the app: it must start with one /, not // (which a URL parser reads as another host) or a full https:// address.
cd ~/go-router-demo/shelf_app
cat > lib/redirect.dart <<'EOF'
/// Returns where to send the reader instead of [uri], or null to let them in.
String? signInRedirect({required bool signedIn, required Uri uri}) {
final onSignIn = uri.path == '/sign-in';
if (!signedIn && !onSignIn) {
return Uri(path: '/sign-in', queryParameters: {'from': uri.toString()})
.toString();
}
if (signedIn && onSignIn) {
final from = uri.queryParameters['from'];
final isAppPath =
from != null && from.startsWith('/') && !from.startsWith('//');
return isAppPath ? from : '/books';
}
return null;
}
EOFNow write a test for each rule. test/ is where Flutter looks for tests:
cd ~/go-router-demo/shelf_app
mkdir -p test
cat > test/redirect_test.dart <<'EOF'
import 'package:flutter_test/flutter_test.dart';
import 'package:shelf_app/redirect.dart';
void main() {
test('a signed-out reader goes to sign-in and keeps the address', () {
final target = signInRedirect(signedIn: false, uri: Uri.parse('/books/2'));
final uri = Uri.parse(target!);
expect(uri.path, '/sign-in');
expect(uri.queryParameters['from'], '/books/2');
});
test('a signed-out reader may open the sign-in screen', () {
expect(signInRedirect(signedIn: false, uri: Uri.parse('/sign-in')), isNull);
});
test('a signed-in reader passes straight through', () {
expect(signInRedirect(signedIn: true, uri: Uri.parse('/books/2')), isNull);
});
test('signing in returns the reader to the saved address', () {
final uri = Uri.parse('/sign-in?from=%2Fbooks%2F2');
expect(signInRedirect(signedIn: true, uri: uri), '/books/2');
});
test('a from value outside the app is ignored', () {
final full = Uri.parse('/sign-in?from=https%3A%2F%2Fexample.com');
final twoSlashes = Uri.parse('/sign-in?from=%2F%2Fexample.com');
expect(signInRedirect(signedIn: true, uri: full), '/books');
expect(signInRedirect(signedIn: true, uri: twoSlashes), '/books');
});
}
EOFCheck it worked
cd ~/go-router-demo/shelf_app
flutter test test/redirect_test.dartThe run should end with All tests passed! and a count of five tests. The first run takes a minute while Flutter downloads its test engine.
Step 5 · Wire up the router
Now describe the whole app as a tree of routes. Create lib/router.dart:
cd ~/go-router-demo/shelf_app
cat > lib/router.dart <<'EOF'
import 'package:go_router/go_router.dart';
import 'auth.dart';
import 'redirect.dart';
import 'screens.dart';
GoRouter buildRouter(AuthState auth, {String initialLocation = '/books'}) {
return GoRouter(
initialLocation: initialLocation,
// Run the redirect again whenever the reader signs in or out.
refreshListenable: auth,
redirect: (context, state) =>
signInRedirect(signedIn: auth.signedIn, uri: state.uri),
errorBuilder: (context, state) =>
NotFoundScreen(location: state.uri.toString()),
routes: [
GoRoute(
path: '/sign-in',
builder: (context, state) => SignInScreen(onSignIn: auth.signIn),
),
StatefulShellRoute.indexedStack(
builder: (context, state, navigationShell) =>
AppShell(navigationShell: navigationShell),
branches: [
StatefulShellBranch(
routes: [
GoRoute(
path: '/books',
builder: (context, state) => const BooksScreen(),
routes: [
GoRoute(
path: ':id',
builder: (context, state) =>
BookScreen(id: state.pathParameters['id']!),
),
],
),
],
),
StatefulShellBranch(
routes: [
GoRoute(
path: '/account',
builder: (context, state) =>
AccountScreen(onSignOut: auth.signOut),
),
],
),
],
),
],
);
}
EOFRead the tree from the outside in:
/sign-insits at the top level, outside the shell, so it fills the screen with no bottom bar.StatefulShellRoute.indexedStackholds one branch per tab. Each branch has its ownNavigator, and the shell keeps every visited branch alive offstage, so the Books tab still shows the book you opened when you come back from Account.:idis a path parameter. It is nested under/books, so/books/2builds two screens, the list and then the book, and the back arrow appears by itself. The value always arrives as a string instate.pathParameters.errorBuilderhandles any address that matches no route, such as a mistyped link.
Then replace lib/main.dart. The router is created once, in State, so a rebuild or a hot reload does not throw away the reader's place:
cd ~/go-router-demo/shelf_app
cat > lib/main.dart <<'EOF'
import 'package:go_router/go_router.dart';
import 'package:material_ui/material_ui.dart';
import 'auth.dart';
import 'router.dart';
void main() {
runApp(ShelfApp(auth: AuthState()));
}
class ShelfApp extends StatefulWidget {
const ShelfApp({
super.key,
required this.auth,
this.initialLocation = '/books',
});
final AuthState auth;
final String initialLocation;
@override
State<ShelfApp> createState() => _ShelfAppState();
}
class _ShelfAppState extends State<ShelfApp> {
late final GoRouter _router = buildRouter(
widget.auth,
initialLocation: widget.initialLocation,
);
@override
void dispose() {
_router.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return MaterialApp.router(title: 'Shelf', routerConfig: _router);
}
}
EOFinitialLocation is a constructor argument only so that tests can start the app at any address. Your phone always starts at /books unless a deep link says otherwise.
Check it worked
cd ~/go-router-demo/shelf_app
flutter analyzeYou should see No issues found!. Then run the app on whatever device you have:
flutter runYou land on Sign in. Press Continue as guest and the Library appears, with no navigation code in the button. Open a book, switch to Account and back, and the book is still open.
Step 6 · Prove the navigation with widget tests
Manual taps prove it once. Widget tests prove it on every change. These tests build the real app, with the real router, and drive it the way a reader would:
cd ~/go-router-demo/shelf_app
cat > test/navigation_test.dart <<'EOF'
import 'package:flutter_test/flutter_test.dart';
import 'package:shelf_app/auth.dart';
import 'package:shelf_app/main.dart';
void main() {
testWidgets('a signed-out reader signs in and reaches the library',
(tester) async {
await tester.pumpWidget(ShelfApp(auth: AuthState()));
await tester.pumpAndSettle();
expect(find.text('Sign in'), findsOneWidget);
await tester.tap(find.text('Continue as guest'));
await tester.pumpAndSettle();
expect(find.text('Library'), findsOneWidget);
});
testWidgets('a link opened while signed out survives sign-in',
(tester) async {
await tester.pumpWidget(
ShelfApp(auth: AuthState(), initialLocation: '/books/2'),
);
await tester.pumpAndSettle();
expect(find.text('Sign in'), findsOneWidget);
await tester.tap(find.text('Continue as guest'));
await tester.pumpAndSettle();
expect(find.text('By Chimamanda Ngozi Adichie'), findsOneWidget);
});
testWidgets('each tab keeps its own history', (tester) async {
await tester.pumpWidget(ShelfApp(auth: AuthState()..signIn()));
await tester.pumpAndSettle();
await tester.tap(find.text('Things Fall Apart'));
await tester.pumpAndSettle();
expect(find.text('By Chinua Achebe'), findsOneWidget);
await tester.tap(find.text('Account'));
await tester.pumpAndSettle();
expect(find.text('Your account'), findsOneWidget);
expect(find.text('By Chinua Achebe'), findsNothing);
await tester.tap(find.text('Books'));
await tester.pumpAndSettle();
expect(find.text('By Chinua Achebe'), findsOneWidget);
});
testWidgets('signing out sends the reader to sign-in', (tester) async {
await tester.pumpWidget(ShelfApp(auth: AuthState()..signIn()));
await tester.pumpAndSettle();
await tester.tap(find.text('Account'));
await tester.pumpAndSettle();
await tester.tap(find.text('Sign out'));
await tester.pumpAndSettle();
expect(find.text('Sign in'), findsOneWidget);
});
testWidgets('an unknown book ID gets a clear message', (tester) async {
await tester.pumpWidget(
ShelfApp(auth: AuthState()..signIn(), initialLocation: '/books/99'),
);
await tester.pumpAndSettle();
expect(find.text('Book not found'), findsOneWidget);
});
testWidgets('an unknown address gets the not-found screen', (tester) async {
await tester.pumpWidget(
ShelfApp(auth: AuthState()..signIn(), initialLocation: '/nowhere'),
);
await tester.pumpAndSettle();
expect(find.text('Page not found'), findsOneWidget);
});
}
EOFpumpAndSettle waits until every page transition and redirect has finished, which is why it follows each tap. findsNothing on the Account tab works because the Books branch is kept offstage, and finders skip offstage widgets by default.
Check it worked
cd ~/go-router-demo/shelf_app
flutter test test/navigation_test.dartAll six tests should pass. To see one fail, change the /books path in lib/router.dart to /library, run the tests again, read the failures, then change it back.
Step 7 · Choose between passing an object and passing an ID
go_router lets you hand any object to the next screen through extra:
context.go('/books/${book.id}', extra: book);It is tempting, because the detail screen then needs no lookup. It is also fragile. A deep link, a browser refresh or Android restoring your app after it was killed in the background all arrive with only the address, so extra is empty and a screen that depends on it breaks. go_router also has to serialise extra when it stores navigation state, and a custom class like Book needs a codec for that.
Make the address carry everything the screen needs, which usually means an ID, and look the data up on arrival, as BookScreen does. If you have the object already and want to skip a network call, pass it in extra as a shortcut, and keep the ID lookup as the fallback.
The same applies to trust. Treat an ID from a link as a request, not a permission. When the data lives on a server, the server must check that this reader may see book 2, whatever the app sends.
Check it worked
The test a link opened while signed out survives sign-in already proves the ID approach: the app starts with nothing but the address /books/2 and still shows the right author. Open lib/screens.dart and confirm that no screen reads GoRouterState.extra.
Step 8 · Handle the Android back button and predictive back
On Android, the system back button or gesture asks the app to pop a screen. go_router sends it to the navigator of the tab you are in, so back from a book returns to the Library rather than closing the app. Back on the first screen of a tab leaves the app: it does not jump to the previously used tab. Many Android phones, budget models in particular, still use the three-button bar, so readers press back constantly. Test it on purpose.
Write a test that sends the same system back event the Android embedding sends:
cd ~/go-router-demo/shelf_app
cat > test/back_test.dart <<'EOF'
import 'package:flutter_test/flutter_test.dart';
import 'package:shelf_app/auth.dart';
import 'package:shelf_app/main.dart';
void main() {
testWidgets('system back closes the book, not the app', (tester) async {
await tester.pumpWidget(
ShelfApp(auth: AuthState()..signIn(), initialLocation: '/books/1'),
);
await tester.pumpAndSettle();
expect(find.text('By Chinua Achebe'), findsOneWidget);
final handled = await tester.binding.handlePopRoute();
await tester.pumpAndSettle();
expect(handled, isTrue);
expect(find.text('Library'), findsOneWidget);
});
}
EOFPredictive back, from Android 14, lets the reader start the back gesture and see the previous screen slide into view before they let go. Two things make it work in Flutter:
- The page transition. In Flutter 3.50 the Material default on Android is already
PredictiveBackPageTransitionsBuilder, so Shelf needs no theme change. - The manifest flag. Open
android/app/src/main/AndroidManifest.xmland make sure the<application>tag hasandroid:enableOnBackInvokedCallback="true". Add it if it is missing.
<application
android:label="shelf_app"
android:name="${applicationName}"
android:icon="@mipmap/ic_launcher"
android:enableOnBackInvokedCallback="true">With predictive back, the app must know before the gesture starts whether back is allowed, so you cannot cancel it halfway. When a screen holds unsaved work, wrap it in PopScope with canPop: false and ask the reader in onPopInvokedWithResult. The older WillPopScope is deprecated for this reason.
Check it worked
cd ~/go-router-demo/shelf_app
flutter test test/back_test.dartThe test should pass. On an Android 14 or later device with gesture navigation, open a book and slowly drag from the screen edge: the Library should peek out from behind it, and releasing returns you to it.
Step 9 · Open screens from links on Android and iOS
Because every screen has an address, a link such as https://shelf.example.com/books/2 can open Shelf on the right book. Flutter has handled incoming links by default since 3.27, and passes the path to go_router, which runs your redirect first. A signed-out reader who taps a link sees sign-in, then the book. The concepts, custom schemes versus verified https links and why the domain must prove it owns the app, are covered in open Larkfield screens from links. The files below are the Flutter side. Replace shelf.example.com with a domain you control.
On Android, add an intent filter inside the <activity> tag in android/app/src/main/AndroidManifest.xml:
<intent-filter android:autoVerify="true">
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="https" android:host="shelf.example.com" />
</intent-filter>Then serve https://shelf.example.com/.well-known/assetlinks.json. The package name is applicationId in android/app/build.gradle.kts, and the fingerprint is the SHA-256 of your signing certificate (for a Play Store app, copy it from the Play Console's app signing page):
[
{
"relation": ["delegate_permission/common.handle_all_urls"],
"target": {
"namespace": "android_app",
"package_name": "com.example.shelf_app",
"sha256_cert_fingerprints": ["REPLACE_WITH_YOUR_SHA256_FINGERPRINT"]
}
}
]On iOS, open ios/Runner.xcworkspace in Xcode, add the Associated Domains capability to the Runner target, and add applinks:shelf.example.com. Then serve https://shelf.example.com/.well-known/apple-app-site-association, with no file extension, as JSON. The app ID is your Apple team ID, a dot, and the bundle identifier shown in Xcode:
{
"applinks": {
"details": [
{
"appIDs": ["REPLACE_WITH_TEAM_ID.com.example.shelfApp"],
"components": [{ "/": "/books/*" }]
}
]
}
}Check it worked
With the app installed on an emulator or simulator, and the files live on your domain, send it a link. On Android:
adb shell am start -a android.intent.action.VIEW -c android.intent.category.BROWSABLE -d "https://shelf.example.com/books/2" com.example.shelf_appOn an iOS simulator:
xcrun simctl openurl booted "https://shelf.example.com/books/2"Shelf should open on Sign in, and after Continue as guest show Americanah by Chimamanda Ngozi Adichie, the same journey the widget test proves. If Android opens the browser instead, the domain is not verified yet; check that assetlinks.json is served over https with no redirect.
Step 10 · Clean up
When you have finished with Shelf, delete the practice project. This removes the folder and everything in it, including the tests:
cd ~
rm -rf ~/go-router-demoCheck it worked
test ! -e ~/go-router-demo && echo "removed"You should see removed. Flutter itself stays installed for your next project.
Next steps
- Decide whether bottom tabs are right for your app at all: choose a navigation pattern for an app.
Related tutorials
- Write end-to-end mobile tests with MaestroYou will have a small Maestro suite for a mobile app, with stable test IDs in React Native or Flutter, a shared sign-in flow fed by environment variables, smoke and full runs split by tags, and a CI job that runs the smoke flows on an Android emulator.
- Store data in a SwiftUI app with SwiftDataYou will build a small shop stock app that saves suppliers and products on the iPhone with SwiftData, lists them with sorted and filtered queries, survives a schema change through a migration plan, and is checked by tests that run against an in-memory store.
- Store data in a Flutter app with Drift and SQLiteYou will build a small shop credit book in Flutter 3.50 that keeps customers and what they owe in SQLite through Drift 2.35, with typed queries, a join, a list that redraws itself from a watch() stream, a tested schema migration and in-memory tests for all of it.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials