Sub topic 7
Pickers and Date Pickers
Assume you know basic Dart, StatefulWidget, setState, BuildContext, and MaterialApp or CupertinoApp. This chapter uses Cupertino widgets to let users choose a value from a scrolling wheel.
Choosing a value with CupertinoPicker
CupertinoPicker displays a list of values in the iOS wheel-picker style. The widget reports the selected item by its integer index. Your state must convert that index into the actual value.
The picker needs a fixed height. Without a height constraint, it can fail to lay out correctly inside a column or modal sheet.
import 'package:flutter/cupertino.dart';
void main() => runApp(const PickerApp());
class PickerApp extends StatelessWidget {
const PickerApp({super.key});
@override
Widget build(BuildContext context) {
return const CupertinoApp(home: PickerPage());
}
}
class PickerPage extends StatefulWidget {
const PickerPage({super.key});
@override
State<PickerPage> createState() => _PickerPageState();
}
class _PickerPageState extends State<PickerPage> {
final _units = ['Kilograms', 'Pounds', 'Ounces'];
int _selectedUnit = 0;
DateTime _selectedDate = DateTime.now();
Future<void> _chooseUnit() {
return showCupertinoModalPopup<void>(
context: context,
builder: (context) {
return Container(
height: 280,
color: CupertinoColors.systemBackground.resolveFrom(context),
child: CupertinoPicker(
itemExtent: forty,
useMagnifier: true,
magnification: 1.15,
onSelectedItemChanged: (index) {
setState(() => _selectedUnit = index);
},
children: [
for (final unit in _units) Center(child: Text(unit)),
],
),
);
},
);
}
Future<void> _chooseDate() {
return showCupertinoModalPopup<void>(
context: context,
builder: (context) {
return Container(
height: 300,
color: CupertinoColors.systemBackground.resolveFrom(context),
child: CupertinoDatePicker(
mode: CupertinoDatePickerMode.date,
initialDateTime: _selectedDate,
onDateTimeChanged: (date) {
setState(() => _selectedDate = date);
},
),
);
},
);
}
@override
Widget build(BuildContext context) {
return CupertinoPageScaffold(
navigationBar: const CupertinoNavigationBar(
middle: Text('Pickers'),
),
child: SafeArea(
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text('Unit: ${_units[_selectedUnit]}'),
CupertinoButton(
onPressed: _chooseUnit,
child: const Text('Choose unit'),
),
Text(
'Date: ${_selectedDate.year}-'
'${_selectedDate.month.toString().padLeft(2, '0')}-'
'${_selectedDate.day.toString().padLeft(2, '0')}',
),
CupertinoButton(
onPressed: _chooseDate,
child: const Text('Choose date'),
),
],
),
),
),
);
}
}In this example, replace forty with 40. The picker stores an index, while the date picker reports a DateTime directly. Both callbacks can run many times while the user scrolls, so keep their work small.
Selecting dates with CupertinoDatePicker
CupertinoDatePicker supports date, time, and date-and-time modes. Its callback receives a new DateTime whenever a wheel changes. The callback may report intermediate values before the user finishes scrolling.
Use minimumDate and maximumDate when your domain has limits, such as preventing a future birth date. Use minuteInterval for time selection, but ensure the interval divides evenly into 60.
Common errors and design choices
- Treating a
CupertinoPickerindex as the final value. Look up the item in your list first. - Omitting a height constraint. Put the picker in a
SizedBoxor a container with a fixed height. - Updating expensive data on every callback. Store the draft value and save it only when the user taps Done if necessary.
- Forgetting that a date picker in time mode still returns a
DateTime. Read only the fields relevant to the selected mode. - Assuming a date has a meaningful time zone without deciding how your application stores dates.
Exercise
Why does CupertinoPicker return an integer instead of the selected string?
Show answer
The picker represents a position in its children. Use that integer as an index into the list of strings.