RadioButton

A material design radio button. Radio button are used in groups. In a group only one button can be selected. The radio button itself does not maintain any state. Instead, selecting the radio invokes the onChanged callback, passing value as a parameter. If groupValue and value match, this radio will be selected. Most widgets will respond to onChanged by calling State.setState to update the radio button's groupValue.

Properties

activeColor

The color to use when this radio button is selected. This specifies the background color of the radio button.

groupValue

The currently selected value for a group of radio buttons. The value can be any type which a developer will decide. If the value is matched with groupValue then the radio button will be selected.

onChanged

Called when the user selects this radio button.

value

The value represented by this radio button. Values must be unique accros the radio button group.

Example

// Declare this variable
int selectedRadio;
 
@override
void initState() {
  super.initState();
  selectedRadio = 0;
}
 
// Changes the selected value on 'onChanged' click on each radio button
setSelectedRadio(int val) {
  setState(() {
    selectedRadio = val;
  });
}
 
// This goes to the build method 
ButtonBar(
  alignment: MainAxisAlignment.center,
  children: <Widget>[
    Radio(
      value: 1,
      groupValue: selectedRadio,
      activeColor: Colors.green,
      onChanged: (val) {
        print("Radio $val");
        setSelectedRadio(val);
      },
    ),
    Radio(
      value: 2,
      groupValue: selectedRadio,
      activeColor: Colors.blue,
      onChanged: (val) {
        print("Radio $val");
        setSelectedRadio(val);
      },
    ),
  ],
)

In the above example, we declared a variable selectedRadio which we have used it as groupValue. Initially it is set to 0, which doesn't match with any radiobutton's value. That means no radio button will be selected initially. When we tap any of the radio button, it invokes the onChanged method with the value that was given to it. In setState method, we set the selectedRadio variable to that value. This will cause other radio button to be deselected as the groupValue will not match.

To select a radio button initially you must set the groupValue to the particular radio button value to match with it.