I’m having difficulty toggling between the check boxes. What i want is the when one checkbox is checked and if the user checks the other checkbox the previous one should uncheck and viceversa.
class _HomeScreenState extends State<HomeScreen> {
@override
Widget build(BuildContext context) {
bool mIsChecked = false;
bool fIsChecked = false;
Size size = MediaQuery.of(context).size;
return Scaffold(
appBar: AppBar(
title: const Text(
'BMI Calculator',
style: TextStyle(fontSize: 15),
),
centerTitle: true,
elevation: 0,
),
body: Column(
children: [
TextContainer(
size: size,
text: 'I am a ',
),
const SizedBox(height: 50),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Column(
children: [
const CircleImage(gender: 'male'),
StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return Transform.scale(
scale: 1.5,
child: Checkbox(
value: mIsChecked,
onChanged: (bool? value) {
setState(() {
if (fIsChecked == true) {
fIsChecked = false;
}
mIsChecked = value!;
});
// print('isChecked: $isChecked');
},
// activeColor: Colors.green,
fillColor: MaterialStateProperty.resolveWith<Color>(
(Set<MaterialState> states) {
if (states.contains(MaterialState.disabled)) {
return const Color(0xFF00BB6E).withOpacity(.32);
}
return const Color(0xFF00BB6E);
}),
materialTapTargetSize: MaterialTapTargetSize.padded,
),
);
},
),
],
),
Column(
children: [
const CircleImage(gender: 'female'),
StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return Transform.scale(
scale: 1.5,
child: Checkbox(
value: fIsChecked,
onChanged: (bool? value) {
setState(() {
if (mIsChecked == true) {
mIsChecked = false;
}
fIsChecked = value!;
});
// print('isChecked: $isChecked');
},
// activeColor: Colors.green,
fillColor: MaterialStateProperty.resolveWith<Color>(
(Set<MaterialState> states) {
if (states.contains(MaterialState.disabled)) {
return const Color(0xFF00BB6E).withOpacity(.32);
}
return const Color(0xFF00BB6E);
}),
materialTapTargetSize: MaterialTapTargetSize.padded,
),
);
},
),
],
),
],
)
],
),
);
}
}
i have tried using different checks but i thing i’m doing something wrong with the conditional that is why it’s not toggling.
2
Answers
You just have to declare the Boolean values outside the build context. Build context method is called whenever the state is changed. Since you declare and assign values inside the build context function, variables are getting the default value. Also, you don’t need stateful builder.
Full Code : –
Output : –
Normally you use radio buttons instead of check boxes when you want only one option to be selected.
Here is a link to documentation on the radio class: https://api.flutter.dev/flutter/material/Radio-class.html