RadioButton Widget – Flutter Guide By Flutter Agency

· 6 min read
RadioButton Widget - Flutter Guide By Flutter Agency
RadioButton Widget - Flutter Guide By Flutter Agency

What is RadioButton Widget ?

RadioButton Widget itself does not maintain any state. When one radio button in a group is selected, the others are un-selected. This means only one option is accepted at the same time. Instead, when the state of the radio button changes, the widget calls the onChanged callback to listen for the onChanged callback and rebuild the Radio Button with groupValue to update state variables.

Code Snippet :

 Radio(
      value: 1,
      groupValue: selectedRadio,
      activeColor: Colors.green,
      onChanged: (val) {
        print("Radio $val");
        setSelectedRadio(val);
      },
    ),

Properties :

value: value attribute contains the value of each radio button.

groupValue: groupValue property is the value that decides whether the radio button in the group should be selected or not.

activeColor: activeColor property decides the active color of the radio button.

onChanged: onChanged returns the current radio button’s value.

Add RadioButton widget to screen using Code snippet as below :

// 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);
      },
    ),
  ],
)

The above code snippet will give us the output :

Radio-Button

RadioButton Widget

 RadioListTile :

RadioListTile gives us more control over the normal one. It has an additional ‘title‘ and ‘subtitle‘ property and a ‘secondary‘ widget.

int selectedRadioTile;
 
@override
void initState() {
  super.initState();
  selectedRadio = 0;
  selectedRadioTile = 0;
}
 
setSelectedRadioTile(int val) {
  setState(() {
    selectedRadioTile = val;
  });
}
 
// This goes to the build method
RadioListTile(
  value: 1,
  groupValue: selectedRadioTile,
  title: Text("Radio 1"),
  subtitle: Text("Radio 1 Subtitle"),
  onChanged: (val) {
    print("Radio Tile pressed $val");
    setSelectedRadioTile(val);
  },
  activeColor: Colors.red,
  secondary: OutlineButton(
    child: Text("Radio List Tile"),
    onPressed: () {
      print("Say Hello");
    },
  ),
  selected: true,
),
RadioListTile(
  value: 2,
  groupValue: selectedRadioTile,
  title: Text("Radio 2"),
  subtitle: Text("Radio 2 Subtitle"),
  onChanged: (val) {
    print("Radio Tile pressed $val");
    setSelectedRadioTile(val);
  },
  activeColor: Colors.red,
  secondary: OutlineButton(
    child: Text("Radio List Tile"),
    onPressed: () {
      print("Say Hello");
    },
  ),
  selected: false,
),

The above code will give us output like below :

RadioListTileExample

RadioList Tile Example

First Define User Class like below :

class User { 
int userId; 
String firstName; 
String lastName; 
User({
this.userId, 
this.firstName, 
this.lastName,
}); 
static List<User> getUsers() { 
return <User>[ 
User(userId: 1, firstName: "Aaron", lastName: "Jackson"), 
User(userId: 2, firstName: "Ben", lastName: "John"), 
User(userId: 3, firstName: "Carrie", lastName: "Brown"),
User(userId: 4, firstName: "Deep", lastName: "Sen"),
User(userId: 5, firstName: "Emily", lastName: "Jane"),
 ];
 }
 }

The complete Source code will look like below :

import 'package:flutter/material.dart';
import 'package:multiImagePicker/model/User.dart';

class RadioButtonWidget extends StatefulWidget {
  @override
  _RadioButtonWidgetState createState() => _RadioButtonWidgetState();
}

class _RadioButtonWidgetState extends State<RadioButtonWidget> {
  List<User> users;
  User selectedUser;
  int selectedRadio;
  int selectedRadioTile;

  @override
  void initState() {
    super.initState();
    selectedRadio = 0;
    selectedRadioTile = 0;
    users = User.getUsers();
  }

  setSelectedRadio(int val) {
    setState(() {
      selectedRadio = val;
    });
  }

  setSelectedRadioTile(int val) {
    setState(() {
      selectedRadioTile = val;
    });
  }

  setSelectedUser(User user) {
    setState(() {
      selectedUser = user;
    });
  }

  List<Widget> createRadioListUsers() {
    List<Widget> widgets = [];
    for (User user in users) {
      widgets.add(
        RadioListTile(
          value: user,
          groupValue: selectedUser,
          title: Text(user.firstName),
          subtitle: Text(user.lastName),
          onChanged: (currentUser) {
            print("Current User ${currentUser.firstName}");
            setSelectedUser(currentUser);
          },
          selected: selectedUser == user,
          activeColor: Colors.green,
        ),
      );
    }
    return widgets;
  }

  @override
  Widget build(BuildContext context) {
    return ListView(
      children: <Widget>[
        Column(
          mainAxisAlignment: MainAxisAlignment.start,
          children: <Widget>[
            Container(
              padding: EdgeInsets.all(20.0),
              child: Text("USERS"),
            ),
            Column(
              children: createRadioListUsers(),
            ),
            Divider(
              height: 20,
              color: Colors.green,
            ),
            RadioListTile(
              value: 1,
              groupValue: selectedRadioTile,
              title: Text("Radio 1"),
              subtitle: Text("Radio 1 Subtitle"),
              onChanged: (val) {
                print("Radio Tile pressed $val");
                setSelectedRadioTile(val);
              },
              activeColor: Colors.red,
              secondary: OutlineButton(
                child: Text("Radio List Tile"),
                onPressed: () {
                  print("Say Hello");
                },
              ),
              selected: true,
            ),
            RadioListTile(
              value: 2,
              groupValue: selectedRadioTile,
              title: Text("Radio 2"),
              subtitle: Text("Radio 2 Subtitle"),
              onChanged: (val) {
                print("Radio Tile pressed $val");
                setSelectedRadioTile(val);
              },
              activeColor: Colors.red,
              secondary: OutlineButton(
                child: Text("Radio List Tile"),
                onPressed: () {
                  print("Say Hello");
                },
              ),
              selected: false,
            ),
            Divider(
              height: 20,
              color: Colors.green,
            ),
            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 code, we have used RadioListTile, Divider widget. You can read separate articles for them.

This will give us output like below :

Radio-Button

RadioButton Example

Thanks for reading !!!

Leave a Reply