Sub topic 3
Screens with CupertinoPageScaffold and CupertinoNavigationBar
This chapter assumes you know basic Dart, StatelessWidget, StatefulWidget, setState, MaterialApp, Scaffold, Navigator, and BuildContext. You will learn the Cupertino equivalents for laying out an iOS-style screen.
The screen structure
CupertinoPageScaffold is the main page container in the Cupertino library. It provides a navigation bar area and a content area. Its navigationBar property receives a CupertinoNavigationBar, while its child property receives the page body.
CupertinoNavigationBar is an iOS-style top bar. The middle widget usually contains the page title. The leading widget appears on the left, and the trailing widget appears on the right.
The structure is usually:
Build a complete screen
The following app creates a single Cupertino screen with a title, a trailing action, and centered content.
import 'package:flutter/cupertino.dart';
void main() {
runApp(const SettingsApp());
}
class SettingsApp extends StatelessWidget {
const SettingsApp({super.key});
@override
Widget build(BuildContext context) {
return const CupertinoApp(
home: SettingsPage(),
);
}
}
class SettingsPage extends StatelessWidget {
const SettingsPage({super.key});
@override
Widget build(BuildContext context) {
return CupertinoPageScaffold(
navigationBar: CupertinoNavigationBar(
middle: const Text('Settings'),
trailing: CupertinoButton(
padding: EdgeInsets.zero,
onPressed: _showHelp,
child: const Icon(CupertinoIcons.question_circle),
),
),
child: SafeArea(
child: Center(
child: Text(
'Change your preferences here.',
style: CupertinoTheme.of(context)
.textTheme
.textStyle,
),
),
),
);
}
void _showHelp() {
// Add an action, such as opening a help page.
}
}SafeArea adds padding around content that could be hidden by a device notch, status bar, or home indicator. Put it around the body when the content should avoid those system areas.
The navigation bar has a fixed visual role. Keep its title short, and use leading or trailing for small actions. For larger controls, place them in the page body instead.
A CupertinoPageScaffold does not automatically make its body scrollable. For long content, use a ListView, CustomScrollView, or another scrolling widget as the child of SafeArea.
Common errors
- Forgetting
SafeArea, which can let content overlap system UI. - Putting a
CupertinoNavigationBarin the body instead of thenavigationBarproperty. - Expecting the body to scroll without adding a scrolling widget.
- Using Material widgets without checking whether their spacing and behavior fit the Cupertino screen.
- Calling
setStatefrom aStatelessWidgetwhen the page needs changing data.
Exercise
Where should a page title go, and how should long page content be made scrollable?
Show answer
Put the title in CupertinoNavigationBar.middle, and use a scrolling widget such as ListView inside the SafeArea body.