Sub topic 5
Cupertino routes, swipe-back and tab scaffolds
This chapter covers how Cupertino screens are pushed and popped, how the iOS swipe-back gesture works, and how CupertinoTabScaffold keeps a separate navigation stack for each tab. It assumes you know Navigator.push and pop, BuildContext, StatefulWidget, and the CupertinoApp and CupertinoPageScaffold setup from earlier chapters.
What CupertinoPageRoute adds
CupertinoPageRoute<T> is a page route that behaves like a native iOS push:
- The new page slides in from the right, and the old page moves left at a reduced speed (a parallax effect).
- The user can drag from the left edge to pop the route. The page follows the finger, and the pop can be cancelled by releasing early.
- The back button in a
CupertinoNavigationBarshows a chevron and a label. The label is the previous route'stitle, or "Back" if none is set. - With
fullscreenDialog: true, the page slides up from the bottom instead. This is the iOS modal presentation, and it has no swipe-back from the edge.
Navigator.of(context).push(
CupertinoPageRoute<void>(
title: 'Inbox',
builder: (context) => const DetailPage(),
),
);The title belongs to the route being pushed. The page after it uses that title as its back label. Pushing a route titled "Inbox" therefore makes the next page's back button read "Inbox".
Swipe-back on MaterialPageRoute
Swipe-back is not exclusive to CupertinoPageRoute. MaterialPageRoute takes its transition from ThemeData.pageTransitionsTheme, and the default builder for iOS and macOS is CupertinoPageTransitionsBuilder. A MaterialApp running on iOS therefore already slides pages and supports the edge swipe. On Android the same code uses the Material transition. This is why many apps only need CupertinoPageRoute when they are inside a CupertinoApp or want the iOS transition on every platform.
| Route type | Transition on iOS | Transition on Android | Edge swipe-back |
|---|---|---|---|
| `CupertinoPageRoute` | iOS slide | iOS slide | Yes, on every platform |
| `MaterialPageRoute` | iOS slide | Material transition | Yes, on iOS only |
| `CupertinoPageRoute` with `fullscreenDialog: true` | Slide up | Slide up | No |
Swipe-back and its gotchas
The back gesture is enabled only when the route can be popped by the user. Flutter checks several conditions, and any one of them disables the gesture:
- The route is the first one in its navigator, so there is nothing to pop to.
- The route is a full-screen dialog.
- A
PopScopewithcanPop: falseis in the route's subtree. The olderWillPopScopehas the same effect. - Another gesture is already in progress on the same route.
The third condition is the usual cause of the complaint "swipe-back stopped working". On iOS, canPop: false blocks the gesture entirely, because the system cannot ask the user "discard changes?" in the middle of a drag. A standard solution is to set canPop to false only while there is something to protect, and to show your own confirmation when the user taps the back button.
import 'package:flutter/cupertino.dart';
class EditorPage extends StatefulWidget {
const EditorPage({super.key});
@override
State<EditorPage> createState() => _EditorPageState();
}
class _EditorPageState extends State<EditorPage> {
bool _dirty = false;
Future<void> _confirmDiscard() async {
final discard = await showCupertinoDialog<bool>(
context: context,
builder: (context) => CupertinoAlertDialog(
title: const Text('Discard changes?'),
actions: [
CupertinoDialogAction(
onPressed: () => Navigator.pop(context, false),
child: const Text('Keep editing'),
),
CupertinoDialogAction(
isDestructiveAction: true,
onPressed: () => Navigator.pop(context, true),
child: const Text('Discard'),
),
],
),
);
if (discard == true && mounted) {
Navigator.pop(context);
}
}
@override
Widget build(BuildContext context) {
return PopScope(
canPop: !_dirty,
onPopInvokedWithResult: (didPop, result) {
if (!didPop) _confirmDiscard();
},
child: CupertinoPageScaffold(
navigationBar: const CupertinoNavigationBar(middle: Text('Editor')),
child: SafeArea(
child: Center(
child: CupertinoSwitch(
value: _dirty,
onChanged: (value) => setState(() => _dirty = value),
),
),
),
),
);
}
}In this example the switch stands in for "the user typed something". While it is on, tapping the back button shows the dialog, but the edge swipe does nothing.
Tab scaffolds
iOS tab bars have a specific behavior: each tab remembers where you were. If you open a message in the Inbox tab, switch to Settings, and return, the message is still open. CupertinoTabScaffold models this by giving each tab its own Navigator. It does this through CupertinoTabView.
CupertinoTabScaffoldtakes atabBar(aCupertinoTabBar) and atabBuilderthat returns the content for tabindex.CupertinoTabViewis a widget that wraps its content in a nestedNavigator. Pushes made from inside it affect only that tab.- Tabs are built lazily the first time they are selected, and the scaffold keeps their state afterwards.
The next app uses two tabs. The Inbox tab pushes a detail page inside its own stack. The detail page opens a compose screen on the root navigator, so the compose screen covers the tab bar.
import 'package:flutter/cupertino.dart';
void main() => runApp(const CupertinoApp(home: RootTabs()));
class RootTabs extends StatelessWidget {
const RootTabs({super.key});
@override
Widget build(BuildContext context) {
return CupertinoTabScaffold(
tabBar: CupertinoTabBar(
items: const [
BottomNavigationBarItem(
icon: Icon(CupertinoIcons.mail),
label: 'Inbox',
),
BottomNavigationBarItem(
icon: Icon(CupertinoIcons.settings),
label: 'Settings',
),
],
),
tabBuilder: (context, index) {
return CupertinoTabView(
builder: (context) =>
index == 0 ? const InboxPage() : const SettingsPage(),
);
},
);
}
}
class InboxPage extends StatelessWidget {
const InboxPage({super.key});
@override
Widget build(BuildContext context) {
return CupertinoPageScaffold(
navigationBar: const CupertinoNavigationBar(middle: Text('Inbox')),
child: SafeArea(
child: ListView(
children: [
for (var i = 1; i <= 3; i++)
CupertinoListTile(
title: Text('Message $i'),
trailing: const CupertinoListTileChevron(),
onTap: () => Navigator.of(context).push(
CupertinoPageRoute<void>(
title: 'Inbox',
builder: (context) => DetailPage(id: i),
),
),
),
],
),
),
);
}
}
class DetailPage extends StatelessWidget {
const DetailPage({super.key, required this.id});
final int id;
@override
Widget build(BuildContext context) {
return CupertinoPageScaffold(
navigationBar: CupertinoNavigationBar(middle: Text('Message $id')),
child: SafeArea(
child: Center(
child: CupertinoButton.filled(
onPressed: () => Navigator.of(context, rootNavigator: true).push(
CupertinoPageRoute<void>(
fullscreenDialog: true,
builder: (context) => const ComposePage(),
),
),
child: const Text('Reply'),
),
),
),
);
}
}
class ComposePage extends StatelessWidget {
const ComposePage({super.key});
@override
Widget build(BuildContext context) {
return CupertinoPageScaffold(
navigationBar: CupertinoNavigationBar(
middle: const Text('New reply'),
leading: CupertinoButton(
padding: EdgeInsets.zero,
onPressed: () => Navigator.of(context).pop(),
child: const Text('Cancel'),
),
),
child: const SafeArea(child: Center(child: Text('Write here'))),
);
}
}
class SettingsPage extends StatelessWidget {
const SettingsPage({super.key});
@override
Widget build(BuildContext context) {
return const CupertinoPageScaffold(
navigationBar: CupertinoNavigationBar(middle: Text('Settings')),
child: SafeArea(child: Center(child: Text('Settings'))),
);
}
}Two details in this code matter:
Navigator.of(context)inInboxPagefinds the tab's navigator, because the page is a descendant of aCupertinoTabView.Navigator.of(context, rootNavigator: true)skips it and finds the app's root navigator. WithoutrootNavigator: true, the compose page would appear inside the Inbox tab with the tab bar still visible.ComposePagecalls plainNavigator.of(context).pop(). Its context sits under the root navigator, so the call pops the right route.
Switching tabs from code
To change tabs programmatically, pass a CupertinoTabController to the scaffold and set its index. Dispose the controller when you own it.
final controller = CupertinoTabController(initialIndex: 0);
// Later, for example after the user saves a message:
controller.index = 1;Common errors
- Back button shows "Back" instead of a title. The previous route has no
title. Settitleon theCupertinoPageRoute. Routes created byMaterialPageRoutedo not provide one. - Tab bar disappears or does not hide. Pages pushed on the tab's navigator keep the tab bar visible. Push on the root navigator to hide it, as
ComposePagedoes. - Android back button closes the app from a nested tab. The system back event goes to the root navigator first in some setups. Test the Android back button on every tab. If it misbehaves, wrap the scaffold in a
PopScopethat forwards the event to the current tab's navigator. - Routes registered in
CupertinoApp.routesare missing inside a tab. ACupertinoTabViewcan take its ownroutesandonGenerateRoute. Named routes defined on the app are not shared with it unless you pass them.
Exercise
A user reports that on iOS they can no longer swipe back from your checkout page, although the back button still works. The page wraps its content in PopScope(canPop: false, ...) to show a "Leave checkout?" dialog. How do you keep the dialog and restore the swipe for the cases where it is safe?
Show answer
canPop: false disables the edge swipe on iOS. Keep a boolean such as _hasUnsavedOrder in state and set canPop: !_hasUnsavedOrder. While the cart is empty or saved, canPop is true and both the button and the swipe work. When there is something to lose, the swipe is blocked and the back button triggers onPopInvokedWithResult, where you show the dialog and pop manually if the user confirms.
Exercise
In the tab app above, the compose page should keep the tab bar hidden, but a teammate pushes it with Navigator.of(context).push(...) from DetailPage and the tab bar stays visible. What is the fix, and why does it work?
Show answer
Use Navigator.of(context, rootNavigator: true).push(...). Plain Navigator.of(context) returns the nearest navigator, which is the one inside the Inbox CupertinoTabView, so the new page is drawn within the tab and below the tab bar. The root navigator sits above the CupertinoTabScaffold, so a route pushed there covers the whole scaffold, including the tab bar.