Sub topic 3
Passing Data to the Next Screen
This chapter assumes you can write Dart with async and await, build screens with Scaffold and AppBar, and push and pop routes with Navigator. Here you will learn the ways to give a destination screen the data it needs, and the mistakes that come with each way.
Why data passing needs a plan
A route is built by a function you hand to MaterialPageRoute. That function creates the destination widget. The destination has no link to the screen that opened it, so it only knows what you give it when it is created.
Flutter offers three common ways to hand data over:
- Constructor parameters.
- Route arguments, read from
ModalRouteorRouteSettings. - Path and query parameters in a URL, used with go_router (covered in a later chapter).
This chapter covers the first two in depth. It also covers what to do when the data is large, changes over time, or must survive a restart.
Constructor parameters
Constructor parameters are the default choice. The destination declares what it needs as final fields, and the compiler checks every call site.
import 'package:flutter/material.dart';
class Product {
const Product({required this.id, required this.name, required this.price});
final int id;
final String name;
final double price;
}
class ProductListScreen extends StatelessWidget {
const ProductListScreen({super.key});
static const _products = [
Product(id: 1, name: 'Keyboard', price: 49.0),
Product(id: 2, name: 'Mouse', price: 19.5),
];
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Products')),
body: ListView(
children: [
for (final product in _products)
ListTile(
title: Text(product.name),
subtitle: Text('\$${product.price}'),
onTap: () {
Navigator.of(context).push(
MaterialPageRoute<void>(
builder: (context) => ProductDetailScreen(product: product),
),
);
},
),
],
),
);
}
}
class ProductDetailScreen extends StatelessWidget {
const ProductDetailScreen({super.key, required this.product});
final Product product;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text(product.name)),
body: Center(child: Text('Price: \$${product.price}')),
);
}
}The builder closure captures product from the list item. If you forget product:, or pass the wrong type, the code does not compile.
When the builder runs
MaterialPageRoute calls builder when the route is first built. It can call it again when the route rebuilds, for example after a theme change or when the route below it changes. The closure still holds the same product, so the screen shows the data from the moment you pushed. If the original list later changes, the open detail screen does not update on its own. Share changing data through state management, or reload it by id.
Route arguments
Named routes cannot call a constructor directly from the call site, so they carry data in an arguments object. The arguments value is typed Object?, so Dart cannot check it for you.
import 'package:flutter/material.dart';
void main() => runApp(const ArgsApp());
class ArgsApp extends StatelessWidget {
const ArgsApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
routes: {
'/': (context) => const StartScreen(),
'/greeting': (context) => const GreetingScreen(),
},
);
}
}
class StartScreen extends StatelessWidget {
const StartScreen({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Start')),
body: Center(
child: ElevatedButton(
onPressed: () {
Navigator.of(context).pushNamed('/greeting', arguments: 'Ada');
},
child: const Text('Greet'),
),
),
);
}
}
class GreetingScreen extends StatelessWidget {
const GreetingScreen({super.key});
@override
Widget build(BuildContext context) {
final name = ModalRoute.of(context)?.settings.arguments as String?;
return Scaffold(
appBar: AppBar(title: const Text('Greeting')),
body: Center(child: Text('Hello, ${name ?? 'stranger'}')),
);
}
}The destination reads the value with ModalRoute.of(context)?.settings.arguments. The cast as String? is a promise that you make to the compiler. If the caller sends an int, the cast throws a TypeError at runtime.
Where you can read the arguments
ModalRoute.of(context) uses context to find the enclosing route. Call it inside build, or in didChangeDependencies if you use a StatefulWidget. Do not call it in initState. At that point the widget cannot yet look up inherited data from context, so the call fails with an assertion error.
A safe pattern in a stateful widget:
import 'package:flutter/material.dart';
class ReportScreen extends StatefulWidget {
const ReportScreen({super.key});
@override
State<ReportScreen> createState() => _ReportScreenState();
}
class _ReportScreenState extends State<ReportScreen> {
int? _reportId;
@override
void didChangeDependencies() {
super.didChangeDependencies();
_reportId ??= ModalRoute.of(context)?.settings.arguments as int?;
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Report')),
body: Center(child: Text('Report id: ${_reportId ?? 'none'}')),
);
}
}The ??= operator stores the value only once. didChangeDependencies can run several times, and this keeps later calls from overwriting state.
Making arguments type-safe
Raw casts spread across the code base are fragile. Wrap the arguments in a small class and read them in one place.
import 'package:flutter/material.dart';
class ProductArgs {
const ProductArgs({required this.id, this.highlight = false});
final int id;
final bool highlight;
}
class ProductRouteScreen extends StatelessWidget {
const ProductRouteScreen({super.key});
static const routeName = '/product';
@override
Widget build(BuildContext context) {
final args = ModalRoute.of(context)!.settings.arguments as ProductArgs;
return Scaffold(
appBar: AppBar(title: Text('Product ${args.id}')),
body: Center(child: Text(args.highlight ? 'Featured' : 'Regular')),
);
}
}
void openProduct(BuildContext context, int id) {
Navigator.of(context).pushNamed(
ProductRouteScreen.routeName,
arguments: ProductArgs(id: id, highlight: true),
);
}The helper openProduct is the only place that builds the arguments, so the call sites stay consistent. The routeName constant also removes string typos from the call sites.
The onGenerateRoute approach from the spine's earlier example goes one step further. It reads settings.arguments, casts it once, and passes the result into a normal constructor. The screen itself then has typed fields and never touches ModalRoute. A later chapter covers it in detail.
Choosing between the two approaches
| Question | Constructor parameters | Route arguments |
|---|---|---|
| Compile-time type checking | Yes | No, it is a runtime cast |
| Works with `pushNamed` | No, unless `onGenerateRoute` builds the screen | Yes |
| Easy to test the screen alone | Yes, create it with any value | Needs a route that supplies arguments |
| Risk of a missing value | Compiler stops you | Null or `TypeError` at runtime |
Use constructor parameters when you push routes directly. Use route arguments when the route is named and you need the name for other reasons, such as analytics.
Common errors
- Reading arguments in
initState. Move the read tobuildordidChangeDependencies. - Casting to a non-null type when the caller may send nothing.
arguments as intthrows ifargumentsisnull. Cast toint?and handlenull, or use!only when a missing value is a bug you want to see. - Sending a mutable object and changing it later. Both screens hold the same object. A change on one screen is visible on the other, but the other screen does not rebuild. Prefer immutable classes with
finalfields. - Sending large data. Pass an
idand load the data in the destination. A large payload held in a route stays in memory as long as the route is on the stack. - Expecting arguments to survive a restart. Arguments live in memory. When the app process is killed and restored, only what the platform restores comes back. If the screen must be reopenable from a link, put the identifier in the URL, which is what go_router's path parameters do.
Exercises
Exercise
A screen reads ModalRoute.of(context)!.settings.arguments as int in initState and crashes on startup. Why does it crash, and where should the read move?
Show answer
In initState the widget cannot yet look up inherited data from its context, so the ModalRoute.of call fails an assertion. Move the read to build or to didChangeDependencies, and store the value with ??= if you keep it in state.
Exercise
Your detail screen receives a Product object through its constructor. The price changes on the list screen while the detail screen is open, but the detail screen shows the old price. Why, and what are two ways to fix it?
Show answer
The detail screen holds the Product captured when the route was pushed, and nothing tells it to rebuild when a different object changes. Fixes: pass only the id and load the current product in the destination, or share the product through a state management solution, such as a ChangeNotifier or a provider, that the detail screen listens to.