I have a parent widget which calls a custom Switch widget that I've made. I need the value of the switch(whether it's ON or OFF) in my parent widget. Can I create a controller in my switch widget which would return that value?
Currently, I am passing the function from my parent widget which changes the value of a boolean which is in my parent widget based on the value of the switch in the switch widget.
Parent widget:
bool isSwitchOn = false;
Switch(onSwitchToggle: (bool val) {
isSwitchOn = val;
})
Custom Switch widget:
class Switch extends StatefulWidget {
Widget build(BuildContext context) {
return CupertinoSwitch(
value: widget.value,
onChanged: (bool value) {
setState(() {
widget.value = value;
});
widget.onSwitchToggle(value);
},
),
}
The switch widget is used everywhere in the code whenever I need a switch and sometimes I don't need to know the state of the switch and I just need to execute a function when the switch is toggled but the way I've written the code, I'll need to pass bool everywhere whenever I call the switch. Looking for a better way to do it. eg: Bool val is unnecessary because i won't need it.
Switch(onSwitchToggle: (bool val) {
print('abc')
})