Sub topic 1
Material and Cupertino: two design languages, one framework
Prerequisites
This chapter assumes you know Dart syntax, can write a StatefulWidget with setState, and have built a simple MaterialApp with a Scaffold. You should also be comfortable with BuildContext.
Material and Cupertino
Flutter ships two widget libraries. Material follows Google's design language and is the default look on Android and the web. Cupertino follows Apple's iOS design language, with its own navigation bars, switches, and fonts. Both libraries are part of the same framework, so you can use either one, or both, in a single app.
The two libraries do not share widgets. Switch is a Material widget, and CupertinoSwitch is its iOS counterpart. Each has its own theme class, too: ThemeData for Material and CupertinoThemeData for Cupertino.
Starting an app with CupertinoApp
CupertinoApp is the root widget for an iOS-style app. It provides navigation, localization, and a theme. Set colors with CupertinoThemeData.
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(
theme: CupertinoThemeData(primaryColor: CupertinoColors.systemIndigo),
home: SettingsPage(),
);
}
}Screens with CupertinoPageScaffold and CupertinoNavigationBar
CupertinoPageScaffold is the page layout. It takes a CupertinoNavigationBar and a child. The navigation bar shows a title in the middle and can hold leading and trailing widgets.
Cupertino controls
The page below uses a switch, a slider, a text field, and a filled button. Each control reports changes through onChanged, and the state lives in the parent widget.
class SettingsPage extends StatefulWidget {
const SettingsPage({super.key});
@override
State<SettingsPage> createState() => _SettingsPageState();
}
class _SettingsPageState extends State<SettingsPage> {
bool _notify = true;
double _volume = 0.5;
String _name = '';
@override
Widget build(BuildContext context) {
return CupertinoPageScaffold(
navigationBar: const CupertinoNavigationBar(middle: Text('Settings')),
child: SafeArea(
child: Column(
children: [
CupertinoSwitch(
value: _notify,
onChanged: (value) => setState(() => _notify = value),
),
CupertinoSlider(
value: _volume,
onChanged: (value) => setState(() => _volume = value),
),
CupertinoTextField(
placeholder: 'Your name',
onChanged: (value) => setState(() => _name = value),
),
Text('Hello, $_name'),
CupertinoButton.filled(
onPressed: () {},
child: const Text('Save'),
),
],
),
),
);
}
}Exercise
Exercise
Why does CupertinoSwitch need a value and an onChanged callback instead of managing its own on or off state?
Show answer
Flutter widgets are rebuilt from their parent's state. The parent owns the value, so the rest of the app can read and change it. The switch reports each change through onChanged, and the parent calls setState to store it.