Sub topic 4
Getting a Result Back from a Screen
This chapter assumes you can write Dart with async and await, build basic Flutter widgets such as Scaffold and AppBar, and push and pop routes with Navigator. It covers how a screen sends a value back to the screen that opened it, and the errors that come with that pattern.
The Future that push returns
Some screens exist to produce a value: a color picker, a date selector, a confirmation dialog. The screen that opened it needs the answer when the user finishes.
Navigator.push returns a Future<T?>. The Future completes when the pushed route is removed from the stack. If the route was removed by Navigator.pop(context, value), the Future completes with value. If it was removed any other way, it completes with null.
Future<void> pickColor(BuildContext context) async {
final color = await Navigator.of(context).push<String>(
MaterialPageRoute<String>(
builder: (context) => const ColorPickerScreen(),
),
);
if (!context.mounted) return;
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Picked: ${color ?? 'nothing'}')),
);
}
class ColorPickerScreen extends StatelessWidget {
const ColorPickerScreen({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Pick a color')),
body: Center(
child: ElevatedButton(
onPressed: () => Navigator.of(context).pop('red'),
child: const Text('Red'),
),
),
);
}
}Three details in this code matter.
- The type argument.
push<String>andMaterialPageRoute<String>both name the result type. The route's type and thepushtype should match. If they differ, Dart can throw a type error when the route completes. - The null check. The result is typed
String?, notString. The code usescolor ?? 'nothing'to handle the missing value. - The
context.mountedcheck. Theawaitsuspends the function. Meanwhile the widget that ownscontextmay have been removed from the tree. Using that context afterward is unsafe, so the code checks first.
What the Future sees over time
The sequence below shows how the two screens communicate. The first screen waits on the Future while the second screen is on top.
The Future is created when you call push. It is held by the route object, not by either screen widget. That is why the value still arrives even though the picker screen is destroyed by the time the Home screen resumes.
Why the result can be null
The Future completes with null in several situations:
- The user presses the AppBar back arrow.
- The user presses the Android system back button or uses the iOS swipe-back gesture.
- The user taps outside a dialog or bottom sheet that is dismissible.
- Your code calls
Navigator.pop(context)without a value. - Another piece of code removes the route with
removeRouteor a similar call.
Treat null as "the user cancelled." A common design is to make cancellation and confirmation both explicit in the type you return. For a yes/no question, a bool? has three states (true, false, null), and many apps treat null the same as false.
Future<bool> confirmDelete(BuildContext context) async {
final confirmed = await Navigator.of(context).push<bool>(
MaterialPageRoute<bool>(
builder: (context) => const ConfirmDeleteScreen(),
),
);
return confirmed ?? false;
}
class ConfirmDeleteScreen extends StatelessWidget {
const ConfirmDeleteScreen({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Delete item?')),
body: Center(
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
TextButton(
onPressed: () => Navigator.of(context).pop(false),
child: const Text('Cancel'),
),
const SizedBox(width: 16),
FilledButton(
onPressed: () => Navigator.of(context).pop(true),
child: const Text('Delete'),
),
],
),
),
);
}
}Wrapping the push in a helper function like confirmDelete keeps the null handling in one place. Callers receive a plain bool.
Returning richer values
A String or bool is enough for simple cases. For several fields, return a small class or a Dart record, so the caller does not have to parse a loose map.
typedef ShippingChoice = ({String method, bool express});
Future<ShippingChoice?> chooseShipping(BuildContext context) {
return Navigator.of(context).push<ShippingChoice>(
MaterialPageRoute<ShippingChoice>(
builder: (context) => const ShippingScreen(),
),
);
}
class ShippingScreen extends StatelessWidget {
const ShippingScreen({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Shipping')),
body: Center(
child: ElevatedButton(
onPressed: () => Navigator.of(context).pop<ShippingChoice>(
(method: 'courier', express: true),
),
child: const Text('Express courier'),
),
),
);
}
}Records require Dart 3 or later. On older versions, define a class instead.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| Lint warning "use_build_context_synchronously", or a crash after `await` | `context` used after the widget was disposed | Check `if (!context.mounted) return;` before using `context` |
| `type 'String' is not a subtype of type 'bool?'` | `pop` value does not match the route's type argument | Use the same type in `push<T>`, `MaterialPageRoute<T>`, and `pop` |
| Caller treats back-button exit as an error | `null` result not handled | Treat `null` as cancel, or default it with `??` |
| Result arrives twice or never | `pop` called in two places, or not called on a path | Make sure each exit path calls `pop` exactly once |
| Value lost after hot restart | Result stored only in the awaiting function's local variable | Save the result into state (a field, a notifier) as soon as it arrives |
Intercepting the back button
Back-button and gesture exits return null by default. If you want these paths to return a value, wrap the screen in a PopScope (covered in a later chapter) and call pop with the value you want from onPopInvokedWithResult. This is optional. Handling null in the caller is usually simpler.
Alternatives to returning a result
Awaiting a pushed route fits one-shot questions: "pick one thing and return." It fits poorly in these cases:
- The value updates continuously. A filter screen where changes should appear live behind it is better served by shared state, such as a
ValueNotifieror a state-management package. - The destination is reached by a URL. With declarative routing,
go_routerofferscontext.push<T>(), which also returns a Future, butcontext.goreplaces the stack and returns no result. You cannot await agocall. - Several screens need the value. Store it in state that all of them read.
Testing a returned result
Widget tests can verify the result by awaiting the Future after tapping the button. This also previews the testing chapter.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('picker returns red', (tester) async {
String? result;
await tester.pumpWidget(
MaterialApp(
home: Builder(
builder: (context) => Scaffold(
body: ElevatedButton(
onPressed: () async {
result = await Navigator.of(context).push<String>(
MaterialPageRoute<String>(
builder: (_) => Scaffold(
body: ElevatedButton(
onPressed: () => Navigator.of(_).pop('red'),
child: const Text('Red'),
),
),
),
);
},
child: const Text('Open'),
),
),
),
),
);
await tester.tap(find.text('Open'));
await tester.pumpAndSettle();
await tester.tap(find.text('Red'));
await tester.pumpAndSettle();
expect(result, 'red');
});
}pumpAndSettle runs frames until the page transition finishes. Without it, the route is still animating and the second tap may miss its target.
Summary
push<T>returns aFuture<T?>that completes when the route is removed.pop(context, value)supplies the value. Any other exit givesnull.- Always handle
null, and checkcontext.mountedafter theawait. - Keep the route type and the
popvalue type consistent. - Use shared state instead when the value changes over time or several screens need it.
Exercise
A settings screen is opened with await Navigator.of(context).push<int>(...). The user changes the font size, then presses the system back button instead of the Save button. What does the awaiting code receive, and how should it handle that?
Show answer
It receives null, because the route was removed without a value passed to pop. The caller should treat null as "no change" (for example, final size = result ?? currentSize;) and, after the await, check context.mounted before using context.
Exercise
Why does context.go('/picker') in go_router not let you write final value = await context.go('/picker')? What would you use instead?
Show answer
context.go replaces the current navigation stack with the location's stack and returns no result Future. Use context.push<T>('/picker'), which adds a route on top of the stack and returns a Future<T?>, and have the picker call context.pop(value).