I just want to have normal radio buttons where only one button in the group can be selected. According to tutorials online we need to set the groupvalue variable to the value in the setState method in onChanged. If i do this i can select all buttons and i dont want this to happen. I want only one button to be a selected at a time(from that group). if there is anything wrong with my code or any other way to do it let me know.
option is the string parameter for title optionvalue is the value for that option.
class Option extends StatefulWidget {
final String option;
final int optionvalue;
Option(this.option, this.optionvalue);
_OptionState createState() => _OptionState();
}
class _OptionState extends State<Option> {
int groupvalue;
@override
Widget build(BuildContext context) {
return Container(
child: Container(
child: RadioListTile(
title: Text(
widget.option,
style: TextStyle(fontSize: 20.0),
),
activeColor: Colors.black,
value: widget.optionvalue,
groupValue: groupvalue,
onChanged: (int a) {
print(a);
setState(() {
groupvalue = a;
});
},
),
),
);
}
}
Try this code
int _groupValue = -1;
@override
Widget build(BuildContext context) {
return Column(
children: <Widget>[
_myRadioButton(
title: "Checkbox 0",
value: 0,
onChanged: (newValue) => setState(() => _groupValue = newValue),
),
_myRadioButton(
title: "Checkbox 1",
value: 1,
onChanged: (newValue) => setState(() => _groupValue = newValue),
),
],
);
}
Widget _myRadioButton({String title, int value, Function onChanged}) {
return RadioListTile(
value: value,
groupValue: _groupValue,
onChanged: onChanged,
title: Text(title),
);
}
Output:
Try this for horizontal radio button list:
int _groupValue = -1;
Container(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Text('Gender', style: TextStyle(fontSize: 18)),
Container(
child: Column(
children: <Widget>[
Row(
children: <Widget>[
Expanded(
flex: 1,
child: RadioListTile(
value: 0,
groupValue: _groupValue,
title: Text("Male"),
onChanged: (newValue) =>
setState(() => _groupValue = newValue),
activeColor: Colors.red,
selected: false,
),
),
Expanded(
flex: 1,
child: RadioListTile(
value: 1,
groupValue: _groupValue,
title: Text("Female"),
onChanged: (newValue) =>
setState(() => _groupValue = newValue),
activeColor: Colors.red,
selected: false,
),
),
],
),
],
),
),
],
),
),
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With