onValueChanged property Null safety

ValueChanged<T?> onValueChanged
final

The callback that is called when a new option is tapped.

This attribute must not be null.

The segmented control passes the newly selected widget's associated key to the callback but does not actually change state until the parent widget rebuilds the segmented control with the new groupValue.

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:

link
class SegmentedControlExample extends StatefulWidget {
  const SegmentedControlExample({super.key});

  @override
  State createState() => SegmentedControlExampleState();
}

class SegmentedControlExampleState extends State<SegmentedControlExample> {
  final Map<int, Widget> children = const <int, Widget>{
    0: Text('Child 1'),
    1: Text('Child 2'),
  };

  int? currentValue;

  @override
  Widget build(BuildContext context) {
    return CupertinoSlidingSegmentedControl<int>(
      children: children,
      onValueChanged: (int? newValue) {
        setState(() {
          currentValue = newValue;
        });
      },
      groupValue: currentValue,
    );
  }
}

Implementation

final ValueChanged<T?> onValueChanged;