Sub topic 7
Pickers and date pickers
Cupertino pickers are the scrolling "drum" controls from iOS. They let a user choose one value from a short list, a date, a time, or a countdown duration. This chapter assumes you can build a StatefulWidget, call setState, and open routes with Navigator. It also assumes you have seen CupertinoPageScaffold from earlier chapters.
The four picker widgets
Flutter ships four picker widgets in package:flutter/cupertino.dart.
| Widget | Chooses | Key parameters |
|---|---|---|
| `CupertinoPicker` | One item from a list you supply | `itemExtent`, `children`, `onSelectedItemChanged`, `scrollController` |
| `CupertinoDatePicker` | A `DateTime` | `mode`, `initialDateTime`, `minimumDate`, `maximumDate`, `onDateTimeChanged` |
| `CupertinoTimerPicker` | A `Duration` | `mode`, `initialTimerDuration`, `minuteInterval`, `onTimerDurationChanged` |
| `CupertinoDatePicker` with `monthYear` mode | A month and year | the same as above |
None of them draws its own container. Each fills whatever space its parent gives it, and it needs a bounded height. The usual presentation is a bottom sheet about 216 logical pixels tall, opened with showCupertinoModalPopup. An inline use inside a form row is also common on iOS, and a fixed-height SizedBox supports it.
The diagram below shows the flow most pickers follow.
A reusable sheet
Every picker needs the same wrapper, so write it once. Save this as picker_sheet.dart.
import 'package:flutter/cupertino.dart';
class PickerSheet extends StatelessWidget {
const PickerSheet({super.key, required this.height, required this.child});
final double height;
final Widget child;
@override
Widget build(BuildContext context) {
return DefaultTextStyle(
style: CupertinoTheme.of(context).textTheme.pickerTextStyle,
child: Container(
height: height,
padding: const EdgeInsets.only(top: 6),
margin: EdgeInsets.only(
bottom: MediaQuery.of(context).viewInsets.bottom,
),
color: CupertinoColors.systemBackground.resolveFrom(context),
child: SafeArea(top: false, child: child),
),
);
}
}Each part solves a specific problem:
resolveFrom(context)turns the dynamic system color into the light or dark variant. Without it, a hard-coded white sheet would glare in dark mode.DefaultTextStylesupplies a text style. A popup route has noMaterialancestor, so under aMaterialAppplainTextcan render with the yellow double underline that marks a missing style.SafeArea(top: false)keeps the wheel above the home indicator.- The
viewInsetsmargin lifts the sheet if a keyboard is open.
CupertinoPicker for a list of choices
CupertinoPicker needs an itemExtent, the fixed height of each row. Every child gets that same height, which is how the wheel can compute its layout without measuring.
import 'package:flutter/cupertino.dart';
import 'picker_sheet.dart';
void main() => runApp(const CupertinoApp(home: FruitPage()));
const _fruits = ['Apple', 'Banana', 'Cherry', 'Mango', 'Peach'];
class FruitPage extends StatefulWidget {
const FruitPage({super.key});
@override
State<FruitPage> createState() => _FruitPageState();
}
class _FruitPageState extends State<FruitPage> {
int _selected = 0;
void _openPicker() {
showCupertinoModalPopup<void>(
context: context,
builder: (context) => PickerSheet(
height: 216,
child: CupertinoPicker(
itemExtent: 32,
scrollController: FixedExtentScrollController(initialItem: _selected),
onSelectedItemChanged: (index) => setState(() => _selected = index),
children: [for (final fruit in _fruits) Center(child: Text(fruit))],
),
),
);
}
@override
Widget build(BuildContext context) {
return CupertinoPageScaffold(
navigationBar: const CupertinoNavigationBar(middle: Text('Fruit')),
child: SafeArea(
child: Center(
child: CupertinoButton(
onPressed: _openPicker,
child: Text('Fruit: ${_fruits[_selected]}'),
),
),
),
);
}
}Points to notice:
onSelectedItemChangedreceives an index, not a value. It fires while the wheel is still moving, and it does not fire for the initial item. Keep your own state initialized to the starting index.- To open on a particular row, pass a
FixedExtentScrollController(initialItem: n). If you keep a controller in aStateobject, dispose it. Creating one inside the builder, as above, is fine for a short-lived popup. - For long or generated lists, use
CupertinoPicker.builderwithitemBuilderandchildCount, so rows build lazily. - Optional looks include
useMagnifier: truewithmagnification: 1.2, anddiameterRatioorsqueezeto change how curved the wheel looks.
CupertinoDatePicker and its modes
CupertinoDatePickerMode selects what the user can change:
date: day, month and year.time: hour, minute and AM/PM.dateAndTime: a weekday and date column plus time columns.monthYear: month and year only, useful for card expiry fields.
On iOS, a Done or Cancel button is a common pattern, so the value changes only when the user confirms. The next example holds the wheel's value in a local variable and commits it on Done.
import 'package:flutter/cupertino.dart';
import 'picker_sheet.dart';
DateTime _dateOnly(DateTime d) => DateTime(d.year, d.month, d.day);
String _format(DateTime d) {
String two(int n) => n.toString().padLeft(2, '0');
return '${d.year}-${two(d.month)}-${two(d.day)}';
}
class BookingDateButton extends StatefulWidget {
const BookingDateButton({super.key});
@override
State<BookingDateButton> createState() => _BookingDateButtonState();
}
class _BookingDateButtonState extends State<BookingDateButton> {
final DateTime _today = _dateOnly(DateTime.now());
late DateTime _date = _today;
void _openPicker() {
var pending = _date;
showCupertinoModalPopup<void>(
context: context,
builder: (context) => PickerSheet(
height: 260,
child: Column(
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
CupertinoButton(
onPressed: () => Navigator.pop(context),
child: const Text('Cancel'),
),
CupertinoButton(
onPressed: () {
setState(() => _date = pending);
Navigator.pop(context);
},
child: const Text('Done'),
),
],
),
Expanded(
child: CupertinoDatePicker(
mode: CupertinoDatePickerMode.date,
initialDateTime: _date,
minimumDate: _today,
maximumDate: DateTime(_today.year, _today.month, _today.day + 90),
onDateTimeChanged: (value) => pending = value,
),
),
],
),
),
);
}
@override
Widget build(BuildContext context) {
return CupertinoButton(
onPressed: _openPicker,
child: Text('Arrival: ${_format(_date)}'),
);
}
}pending is a plain local variable. The picker keeps its own scroll state, so the callback does not need setState. Only the Done button changes the widget's real state.
Constraints that cause assertion errors
The date and timer pickers check their arguments in debug mode. These checks cause most picker crashes.
initialDateTimemust lie betweenminimumDateandmaximumDate, inclusive. If you passDateTime.now()as the initial value and a minimum of "tomorrow", the picker fails.- In
timeanddateAndTimemodes,minuteIntervalmust divide 60 evenly (1, 2, 3, 4, 5, 6, 10, 12, 15, 20, 30). The initial minute must be a multiple of the interval. use24hFormatdefaults tofalse. Read it from the user's settings withMediaQuery.alwaysUse24HourFormatOf(context)if you want the device preference.CupertinoTimerPickertakes aDuration, not aDateTime. Itsmodeishm,msorhms, and itsminuteIntervalandsecondIntervalfollow the same divide-evenly rule.
Locale and the Material alternative
Picker labels such as month names come from CupertinoLocalizations. A CupertinoApp and a MaterialApp both supply English defaults. For other languages, add flutter_localizations and its delegates to your app.
Common mistakes
- Putting a picker in a
ColumnwithoutExpandedor a fixed height. This gives an unbounded height error. - Giving
CupertinoPickerchildren of different heights. TheitemExtentwins and content is clipped. - Hard-coding
Colors.whitefor the sheet background, which breaks dark mode. - Treating
onSelectedItemChangedas a "chosen" event. It reports every row the wheel passes through. - Storing the picked
DateTimewith a time part when you only care about the day, which makes later equality checks fail. Normalize with a helper such as_dateOnly.
Exercise
A CupertinoDatePicker in time mode throws an assertion when you set minuteInterval: 15 and initialDateTime: DateTime(2026, 1, 1, 9, 10). Why, and how do you fix it?
Show answer
With minuteInterval: 15, the initial minute must be a multiple of 15, and 10 is not. Change the initial time to a valid minute such as 9:15 or 9:00, or round the minute in code before passing it, for example (now.minute ~/ 15) * 15.
Exercise
In the fruit example, a user opens the picker and taps outside the sheet without scrolling. Which fruit is shown on the button, and why is that correct?
Show answer
The button still shows the previously selected fruit (Apple on first use). onSelectedItemChanged never fired, so _selected was not changed, and the wheel opened on initialItem: _selected. State already matched what the wheel displayed.