I am new to Flutter, I have created a switch widget with Statefull widget and I am trying to read the value of the switch from the screen to do certain task.
I have built custom switch.
This is my Switch Widget.
class SwitchGlobal extends StatefulWidget {
final bool currentValue;
final String controlText;
final double fontSize;
final FontWeight fontWeight;
const SwitchGlobal({
super.key,
required this.currentValue,
required this.controlText,
required this.fontSize,
required this.fontWeight,
});
@override
State<SwitchGlobal> createState() =>
_SwitchGlobalState(currentValue, controlText, fontSize, fontWeight);
}
class _SwitchGlobalState extends State<SwitchGlobal> {
bool isSwitched = false;
bool currentValue = false;
String labelText = "";
double fontSize = 8;
FontWeight fontWeight = FontWeight.bold;
_SwitchGlobalState(
this.currentValue, this.labelText, this.fontSize, this.fontWeight);
void toggleSwitch(bool value) {
setState(() {
currentValue = !currentValue;
});
}
@override
Widget build(BuildContext context) {
return Container(
child: Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
Text(
labelText,
style: TextStyle(fontSize: fontSize, fontWeight: fontWeight),
),
Switch(
onChanged: toggleSwitch,
value: currentValue,
activeColor: Colors.green,
activeTrackColor: Colors.greenAccent,
inactiveThumbColor: Colors.grey,
inactiveTrackColor: Colors.grey.shade200,
),
],
),
);
}
}
I just wanted to read the value of this switch widget in my screen when a user clicks on a button.
2
Answers
Try to use
SwitchGlobal
widget property likePlease update your switch code with this ;
Use :