The Phantom Back Button: A GoRouter & Async Race Condition
The Bug
Imagine a standard top-level screen in your app—like a dashboard or a settings landing page—where the back button should not appear because there is nowhere to go back to.
From this screen, you open a modal dialog to edit some data. You hit Save, the dialog disappears, but suddenly, a back button appears in your app bar. Tapping it completely crashes the app:
Exception has occurred.
GoError (GoError: There is nothing to pop)
The app bar believes there is a route to pop, but GoRouter insists there isn't.
The Code Before
The App Bar Layout
The layout uses context.canPop() from the go_router package to decide whether to show a back button or a hamburger menu icon.
@override
Widget build(BuildContext context, WidgetRef ref) {
// context.canPop() is used to check if we can navigate backward
final canPop = context.canPop();
return Scaffold(
appBar: AppBar(
leading: canPop
? BackButton(onPressed: () => context.pop())
: IconButton(
icon: const Icon(Icons.menu),
onPressed: () => Scaffold.of(context).openDrawer(),
),
),
body: const DataListScreen(),
);
}
The Edit Dialog Save Button
When saving, the app awaits an asynchronous network or database operation before dismissing the dialog.
ElevatedButton(
onPressed: () async {
// 1. Await the async backend/DB write operation
final success = await _saveData();
// 2. Dismiss the dialog if successful
if (success && context.mounted) {
context.pop();
}
},
child: const Text('Save'),
),
What Was Actually Happening
The bug is a race condition between an async write operation, a state management update (Riverpod), and a widget rebuild—all happening fractions of a second before the dialog is dismissed.
Step-by-Step Breakdown
1. User taps "Save" inside the dialog.
2. _saveData() is awaited, writing the changes to your backend or database.
3. The successful write triggers a Riverpod provider to emit updated data.
4. The parent screen rebuilds because it is watching that updated data provider.
5. The Layout widget rebuilds as a direct result.
6. During this rebuild, context.canPop() is evaluated:
→ The dialog is STILL on the Navigator stack (it hasn't been dismissed yet).
→ context.canPop() evaluates to TRUE.
→ A back button is rendered in the App Bar.
7. _saveData() finishes, and context.pop() finally runs, dismissing the dialog.
8. The Layout widget does NOT rebuild again because no new state change triggers it.
→ The back button is now permanently baked onto the screen.
9. The user taps the phantom back button:
→ context.pop() is called → there are no actual pages left to pop → CRASH.
Why context.canPop() Lied to Us
This is the most subtle part of the issue. In go_router, context.canPop() does not just check GoRouter's declarative route stack. Under the hood, it checks Flutter's raw Navigator stack, which includes everything—GoRouter pages, localized navigation, and modal dialogs pushed via showDialog.
When showDialog opens a modal, Flutter pushes a DialogRoute onto the Navigator stack. At that exact moment, Navigator.canPop() becomes true.
Because our state management triggered a UI rebuild after the async work finished but before the dialog was popped, context.canPop() looked up at the stack, saw the dialog floating on top, and said: "Yep, we can pop!"
The Fix
To fix this, we need to check if the current screen is a top-level route, completely ignoring any temporary modals or dialogs floating above it.
The Updated Layout
@override
Widget build(BuildContext context, WidgetRef ref) {
// Check if the current route is the absolute base of this navigation stack
final canPop = !(ModalRoute.of(context)?.isFirst ?? true);
return Scaffold(
appBar: AppBar(
leading: canPop
? BackButton(onPressed: () => context.pop())
: IconButton(
icon: const Icon(Icons.menu),
onPressed: () => Scaffold.of(context).openDrawer(),
),
),
body: const DataListScreen(),
);
}
Why ModalRoute.of(context)?.isFirst Works
ModalRoute.of(context) fetches the route context for the specific widget calling it—meaning the underlying screen, not the dialog overlaying it.
The isFirst property returns true if there are no navigation routes below this screen. Crucially, dialogs pushed on top of the screen have zero impact on isFirst. It only cares about what is beneath the screen, never what floats above it.
| Scenario | context.canPop() | ModalRoute.of(context)?.isFirst | Resulting canPop |
|---|---|---|---|
| Top-level screen (no dialog) | false | true | false (Menu shows) ✓ |
| Top-level screen (with dialog open) | true | true | false (Menu stays) ✓ |
| Deeply nested sub-route | true | false | true (Back button shows) ✓ |
By switching to isFirst, the race condition is broken. No matter when the parent layout rebuilds—mid-flight during an async save or after a data refresh—the underlying route knows it is at the bottom of the stack. The phantom back button can never appear.
Key Takeaways
context.canPop()is not exclusive to GoRouter. It evaluates the global Flutter Navigator stack, including dialogs and bottom sheets. Do not use it as a strict proxy for "Am I on a top-level page?"- Awaiting async work before popping a dialog causes UI mid-flight states. If your async logic updates a global state provider before closing the dialog, expect your parent screens to rebuild while the dialog is still actively sitting on the stack.
- **Use
ModalRoute.of(context)?.isFirst**when you need to determine if the current screen has history beneath it, completely independent of whatever temporary overlays are stacked on top of it.