Sub topic 4
Cupertino buttons, switches, sliders and text fields
This chapter assumes you can write StatelessWidget and StatefulWidget classes and call setState. It also assumes you have already built a screen with CupertinoApp, CupertinoPageScaffold and CupertinoNavigationBar. Here you will learn how the four most common Cupertino input controls work, how they differ from their Material counterparts, and which layout and state mistakes cause most of the bugs.
The working model
Cupertino controls share three traits.
- They are controlled widgets.
CupertinoSwitchandCupertinoSliderhold no value of their own. You pass the currentvalueand anonChangedcallback, and you store the new value in your own state. If you never callsetState, the control does not move. - They read their colors from
CupertinoTheme. The accent color comes fromprimaryColorinCupertinoThemeData. You rarely need per-widget color overrides. - They do not need a
Materialancestor. Material widgets such asTextFieldandInkWelldraw ink splashes on aMaterialwidget and fail without one. Cupertino controls draw their own feedback, so they work directly underCupertinoPageScaffold.
CupertinoButton
CupertinoButton has three constructors.
| Constructor | Appearance | Typical use |
|---|---|---|
| `CupertinoButton(...)` | Text or icon only, no background | Secondary actions, navigation bar actions |
| `CupertinoButton.tinted(...)` | Background filled with a faded tint of the accent color | Medium-emphasis actions |
| `CupertinoButton.filled(...)` | Solid accent-color background | The main action on a screen |
Every constructor requires child and onPressed. Passing onPressed: null disables the button and renders it in the disabled color. This is how you express "not ready yet", so you do not need a separate enabled flag.
Instead of a Material ripple, the button fades its content to pressedOpacity (0.4 by default) while pressed. You can change that value, along with padding and borderRadius. The default padding is zero for the plain variant and larger for .filled, so a plain button with a short label has a small tap target. Wrap it in padding or set padding explicitly. Touch targets should be at least about 44 logical pixels.
CupertinoSwitch
CupertinoSwitch takes value (a bool) and onChanged (a ValueChanged<bool>?). Setting onChanged to null disables it. It has a fixed intrinsic size of roughly 51 by 31 logical pixels, so it never causes unbounded-width errors, but it does not stretch either. Put it in the trailing slot of a list tile or at the end of a Row.
CupertinoSlider
CupertinoSlider takes value, onChanged, min (default 0.0), max (default 1.0) and an optional divisions. It also offers onChangeStart and onChangeEnd. Use onChanged to update the UI continuously. Use onChangeEnd for expensive work such as saving to disk or calling an API, so you do not do it on every drag frame.
Two differences from Material's Slider:
- There is no value label bubble. If the user needs to see the number, show it in a nearby
Text. - It expands to the width it is given. Inside a
Rowit needsExpanded, or you get a "RenderBox was not laid out" or unbounded-width error.
CupertinoTextField
CupertinoTextField is a rounded, bordered field with a placeholder. It is not a form field, and its decoration model differs from TextField. Instead of an InputDecoration, it exposes separate properties:
placeholderandplaceholderStylereplacehintText.prefixandsuffixaccept any widget, such as an icon.clearButtonModetakes anOverlayVisibilityMode(never,editing,notEditing,always) and controls when the built-in clear button appears.decorationtakes aBoxDecorationfor the border and background.paddingsets the inner padding. The default is small, so most designs increase it.
It also accepts the usual controller, keyboardType, obscureText, textInputAction, onChanged and onSubmitted. There is no errorText. Show validation messages in a separate Text below the field. If you need form validation, use CupertinoTextFormFieldRow inside a Form, which supports a validator.
A complete example
This screen combines all four controls. The Save button is disabled until the name field has text.
import 'package:flutter/cupertino.dart';
void main() => runApp(
const CupertinoApp(
theme: CupertinoThemeData(primaryColor: CupertinoColors.systemIndigo),
home: ProfileForm(),
),
);
class ProfileForm extends StatefulWidget {
const ProfileForm({super.key});
@override
State<ProfileForm> createState() => _ProfileFormState();
}
class _ProfileFormState extends State<ProfileForm> {
final TextEditingController _name = TextEditingController();
bool _notifications = true;
double _volume = 0.5;
String _status = '';
@override
void initState() {
super.initState();
_name.addListener(() => setState(() {}));
}
@override
void dispose() {
_name.dispose();
super.dispose();
}
void _save() {
FocusScope.of(context).unfocus();
setState(() {
_status = 'Saved ${_name.text.trim()} '
'(volume ${(_volume * 100).round()}%)';
});
}
@override
Widget build(BuildContext context) {
final canSave = _name.text.trim().isNotEmpty;
return CupertinoPageScaffold(
navigationBar: const CupertinoNavigationBar(middle: Text('Profile')),
child: SafeArea(
child: Padding(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
CupertinoTextField(
controller: _name,
placeholder: 'Name',
padding: const EdgeInsets.all(12),
clearButtonMode: OverlayVisibilityMode.editing,
textInputAction: TextInputAction.done,
),
const SizedBox(height: 16),
Row(
children: [
const Expanded(child: Text('Notifications')),
CupertinoSwitch(
value: _notifications,
onChanged: (value) => setState(() => _notifications = value),
),
],
),
const SizedBox(height: 16),
Row(
children: [
const Icon(CupertinoIcons.volume_down),
Expanded(
child: CupertinoSlider(
value: _volume,
divisions: 10,
onChanged: (value) => setState(() => _volume = value),
),
),
const Icon(CupertinoIcons.volume_up),
],
),
const SizedBox(height: 24),
CupertinoButton.filled(
onPressed: canSave ? _save : null,
child: const Text('Save'),
),
const SizedBox(height: 16),
Text(_status, textAlign: TextAlign.center),
],
),
),
),
);
}
}Points worth noting in this code:
- The controller listener calls
setStatesocanSaveis recomputed on every keystroke. Without it, the button would stay disabled after typing. _nameis disposed indispose. Forgetting this leaks the controller.- The slider sits in
Expanded, while the switch does not need it. FocusScope.of(context).unfocus()dismisses the keyboard when saving.
Common errors
- The switch or slider does not move. You passed a constant
value, or you changed a variable without callingsetState. - "An InputDecorator... / No Material widget found". This comes from mixing in a Material
TextFieldunder aCupertinoApp. UseCupertinoTextField, or wrap the Material widget in aMaterial. - Unbounded width with
CupertinoTextFieldorCupertinoSliderin aRow. Wrap each inExpandedorSizedBoxwith a width. - A tiny tap target on a plain
CupertinoButton. Add padding, because the default is tight. - Expecting
errorTextor a floating label. Cupertino fields have neither. Build error text yourself.
Quick reference
| Need | Cupertino widget | Key properties |
|---|---|---|
| Primary action | `CupertinoButton.filled` | `onPressed`, `padding`, `borderRadius` |
| On/off setting | `CupertinoSwitch` | `value`, `onChanged` |
| Continuous value | `CupertinoSlider` | `min`, `max`, `divisions`, `onChangeEnd` |
| Free text | `CupertinoTextField` | `controller`, `placeholder`, `clearButtonMode` |
| Validated text | `CupertinoTextFormFieldRow` | `validator`, inside a `Form` |
Exercise
A CupertinoSlider placed directly inside a Row throws a layout error about unbounded width. What fixes it, and why does a CupertinoSwitch in the same Row not have the problem?
Show answer
Wrap the slider in Expanded (or give it a fixed width with SizedBox). A slider tries to fill the width it is offered, and a Row gives its children unbounded width along the main axis, so the slider has no finite size. CupertinoSwitch has a fixed intrinsic size of about 51 by 31 logical pixels, so it needs no constraint from its parent.
Exercise
In the ProfileForm example, you remove the line that adds a listener to _name. You type a name, but the Save button stays disabled. Why, and what are two ways to fix it?
Show answer
Typing changes the text inside the TextEditingController but does not call setState, so build does not run and canSave is never recomputed. Fix it either by adding a listener to the controller that calls setState, or by passing onChanged: (_) => setState(() {}) to the CupertinoTextField.
Exercise
You want to save the slider's value to a server only when the user lifts their finger. Which callback do you use, and which callback keeps the thumb moving during the drag?
Show answer
Use onChangeEnd for the save. Use onChanged, where you call setState to store the new value, to keep the thumb moving.