Sub topic 8
Passing objects with extra and its limits
You can pass a Dart object to a route with the extra parameter of go, push and goNamed. This chapter shows how to use it, why it is fragile, and how to design screens that still work when it is missing. It assumes you know path and query parameters, and the difference between go and push.
What extra is
Every navigation method in go_router accepts an optional extra argument of type Object?. The destination route reads it from GoRouterState.extra.
context.go('/books/42', extra: book);
context.push('/books/42', extra: book);
context.goNamed('book', pathParameters: {'id': '42'}, extra: book);In the route builder, state.extra has the static type Object?. You must check or cast it yourself.
builder: (context, state) {
final book = state.extra as Book; // throws if extra is null or another type
return BookScreen(book: book);
},The object never appears in the URL. It travels next to the location, in memory, and the router hands it to the page created for that navigation.
Why extra is limited
The URL is the only part of a location that go_router can rebuild from nothing. Anything outside the URL can disappear. These are the situations where state.extra is null or has the wrong type:
| Situation | What happens to extra |
|---|---|
| Deep link from outside the app | No `extra` exists, so it is `null`. |
| Browser reload on Flutter web | The in-memory object is gone. The URL is restored, but you should expect `null`. |
| User pastes the URL into a new tab | `null`. |
| Another part of the app navigates to the same location without it | `null`. |
| A redirect sends the user elsewhere | The redirect receives `state.extra`, but you must forward it yourself if you want it kept. |
| Different caller passes a different type | `state.extra` has an unexpected type, and an `as` cast throws. |
Two further points matter for design:
extrais not part of the location's identity. Two navigations to/books/42with differentextravalues are the same URL. The URL bar and the browser history entry look identical.- Objects you pass should be treated as read-only snapshots. If the underlying data changes, the screen shows stale data unless it also listens to your state layer.
The router also has an extraCodec parameter. It lets you supply a codec so extra can be encoded and restored, for example for web history or state restoration. Treat it as an advanced option. The basic rule stays the same: do not make a screen depend on extra being present.
A resilient pattern
Put the identity of the thing in the URL. Treat extra as an optional shortcut that saves a lookup or avoids a loading flash. The example below is complete. The list screen passes the Book it already holds, and the detail route works without it.
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
class Book {
const Book({required this.id, required this.title});
final String id;
final String title;
}
const List<Book> catalog = <Book>[
Book(id: '42', title: 'Dart in Practice'),
Book(id: '7', title: 'Flutter Layouts'),
];
Book? findBook(String id) {
for (final Book book in catalog) {
if (book.id == id) return book;
}
return null;
}
final GoRouter router = GoRouter(
initialLocation: '/',
routes: <RouteBase>[
GoRoute(
path: '/',
builder: (context, state) => const BookListScreen(),
routes: <RouteBase>[
GoRoute(
path: 'books/:id',
name: 'book',
builder: (context, state) {
final String id = state.pathParameters['id']!;
final Object? extra = state.extra;
final Book? book = extra is Book ? extra : findBook(id);
if (book == null) {
return const Scaffold(
body: Center(child: Text('Book not found')),
);
}
return BookScreen(book: book);
},
),
],
),
],
);
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp.router(routerConfig: router);
}
}
class BookListScreen extends StatelessWidget {
const BookListScreen({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Books')),
body: ListView(
children: <Widget>[
for (final Book book in catalog)
ListTile(
title: Text(book.title),
onTap: () => context.go('/books/${book.id}', extra: book),
),
],
),
);
}
}
class BookScreen extends StatelessWidget {
const BookScreen({super.key, required this.book});
final Book book;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text(book.title)),
body: Center(child: Text('Book ${book.id}')),
);
}
}The check extra is Book replaces a blind cast. It handles both null and a wrong type, and it falls back to findBook. In a real app the fallback might be an asynchronous repository call. In that case, show a loading state while the data arrives.
Choosing between path, query and extra
Pick the channel by asking whether the value must survive a reload or a shared link.
- Use a path parameter for identity:
/books/42. - Use a query parameter for small, shareable options such as a sort order or a referrer:
?ref=home. - Use extra only for data that is already in memory, is too large or awkward for a URL, and has a fallback.
Do not put secrets, tokens or passwords in any of these. Path and query values show up in the address bar and in logs, and extra can show up in browser history state.
Common mistakes
- Casting without checking.
state.extra as Bookcrashes on every deep link and web reload. Useisand a fallback. - Using extra for identity. If the screen cannot say which book it shows without
extra, the URL is incomplete. Add the id to the path. - Passing mutable shared objects. The destination and the caller then hold the same instance, and edits on one side leak to the other. Pass immutable values, or an id.
- Expecting extra to survive a redirect. A redirect that returns a new location string drops
extra. Readstate.extrainside the redirect callback if you need to forward it, and remember that a redirect returns only a location string. For guards, keep the destination in the URL, such as afromquery parameter. - Assuming push and go behave differently for extra. Both deliver it to the new page. The difference is in the stack, not in the data.
Testing the fallback
Test both paths. In a widget test, navigate with router.go('/books/42', extra: catalog.first) and expect the title. Then call router.go('/books/42') with no extra, and expect the same title through the lookup. A third test with router.go('/books/999') should show the "Book not found" text. These three tests cover the cases that break in production: a normal tap, a deep link, and a bad id.
Exercise
A product screen is opened with context.push('/products/9', extra: product). A user shares the URL /products/9 and a friend opens it in the app. The builder runs final product = state.extra as Product;. What happens, and how do you fix it?
Show answer
state.extra is null for a link opened from outside, so the cast throws and the screen fails. Fix it by reading the id from state.pathParameters['id'], using state.extra only when state.extra is Product, and otherwise loading the product by id (showing a loading or not-found state while it loads or if it is missing).
Exercise
Name two kinds of data that belong in a path or query parameter rather than in extra, and one kind that suits extra.
Show answer
The identity of a resource (for example a book id) belongs in the path, and a shareable option (for example a sort order) belongs in a query parameter. An object already in memory that would be awkward to encode in a URL suits extra, as long as the screen has a fallback when it is missing.