Add ability to disable CupertinoSegmentedControl (#152813)

### Summary

Add the ability to configure enabled or disabled segments in CupertinoSegmentedControl. The idea is to pass a `segmentStates` map, where the user can set the state according to segment key. User can also set background and text colors when the segment is disabled.

### Demo

https://github.com/user-attachments/assets/4a02da02-a0fb-4ded-a271-033a8dc79ac3

### Related issue
Fixes https://github.com/flutter/flutter/issues/52105
This commit is contained in:
Huy
2024-10-24 19:05:35 +07:00
committed by GitHub
parent 0167f02e90
commit fa5254331f
4 changed files with 315 additions and 9 deletions

View File

@@ -37,6 +37,9 @@ class SegmentedControlExample extends StatefulWidget {
class _SegmentedControlExampleState extends State<SegmentedControlExample> {
Sky _selectedSegment = Sky.midnight;
bool _toggleOne = false;
bool _toggleAll = true;
Set<Sky> _disabledChildren = <Sky>{};
@override
Widget build(BuildContext context) {
@@ -45,6 +48,7 @@ class _SegmentedControlExampleState extends State<SegmentedControlExample> {
navigationBar: CupertinoNavigationBar(
// This Cupertino segmented control has the enum "Sky" as the type.
middle: CupertinoSegmentedControl<Sky>(
disabledChildren: _disabledChildren,
selectedColor: skyColors[_selectedSegment],
// Provide horizontal padding around the children.
padding: const EdgeInsets.symmetric(horizontal: 12),
@@ -73,9 +77,60 @@ class _SegmentedControlExampleState extends State<SegmentedControlExample> {
),
),
child: Center(
child: Text(
'Selected Segment: ${_selectedSegment.name}',
style: const TextStyle(color: CupertinoColors.white),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'Selected Segment: ${_selectedSegment.name}',
style: const TextStyle(color: CupertinoColors.white),
),
const SizedBox(height: 20),
Row(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
const Text('Disable one segment', style: TextStyle(color: CupertinoColors.white)),
CupertinoSwitch(
value: _toggleOne,
onChanged: (bool value) {
setState(() {
_toggleOne = value;
if (value) {
_toggleAll = false;
_disabledChildren = <Sky>{Sky.midnight};
} else {
_toggleAll = true;
_disabledChildren = <Sky>{};
}
});
},
),
],
),
Row(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
const Text('Toggle all segments', style: TextStyle(color: CupertinoColors.white)),
CupertinoSwitch(
value: _toggleAll,
onChanged: (bool value) {
setState(() {
_toggleAll = value;
if (value) {
_toggleOne = false;
_disabledChildren = <Sky>{};
} else {
_disabledChildren = <Sky>{
Sky.midnight,
Sky.viridian,
Sky.cerulean,
};
}
});
},
),
],
),
],
),
),
);