SegmentedControl
sample.packages.flutter.lib.src.cupertino.segmented_control.63.
This example shows a [CupertinoSegmentedControl] with an enum type.
The callback provided to [onValueChanged] should update the state of the parent [StatefulWidget] using the [State.setState] method, so that the parent gets rebuilt; for example:
import 'package:flutter/cupertino.dart';
enum Sky { midnight, viridian, cerulean }
Map skyColors = {
Sky.midnight: const Color(0xff191970),
Sky.viridian: const Color(0xff40826d),
Sky.cerulean: const Color(0xff007ba7),
};
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
static const String _title = 'CupertinoSegmentedControl Sample';
@override
Widget build(BuildContext context) {
return const CupertinoApp(
title: _title,
home: SegmentedControlSample(),
);
}
}
class SegmentedControlSample extends StatefulWidget {
const SegmentedControlSample({Key? key}) : super(key: key);
@override
State createState() => _SegmentedControlSampleState();
}
class _SegmentedControlSampleState extends State {
Sky _selectedSegment = Sky.midnight;
@override
Widget build(BuildContext context) {
return CupertinoPageScaffold(
backgroundColor: skyColors[_selectedSegment],
navigationBar: CupertinoNavigationBar(
// This Cupertino segmented control has the enum "Sky" as the type.
middle: CupertinoSegmentedControl(
selectedColor: skyColors[_selectedSegment],
// Provide horizontal padding around the children.
padding: const EdgeInsets.symmetric(horizontal: 12),
// This represents a currently selected segmented control.
groupValue: _selectedSegment,
// Callback that sets the selected segmented control.
onValueChanged: (Sky value) {
setState(() {
_selectedSegment = value;
});
},
children: const {
Sky.midnight: Padding(
padding: EdgeInsets.symmetric(horizontal: 20),
child: Text(
'Midnight',
style: TextStyle(color: CupertinoColors.white),
),
),
Sky.viridian: Padding(
padding: EdgeInsets.symmetric(horizontal: 20),
child: Text(
'Viridian',
style: TextStyle(color: CupertinoColors.white),
),
),
Sky.cerulean: Padding(
padding: EdgeInsets.symmetric(horizontal: 20),
child: Text(
'Cerulean',
style: TextStyle(color: CupertinoColors.white),
),
),
},
),
),
child: Center(
child: Text(
'Selected Segment: ${_selectedSegment.name}',
style: const TextStyle(color: CupertinoColors.white),
),
),
);
}
}
SHARE: