RadioButton in Flutter

Create Free Backend With Appwrite

Introduction

RadioButtons are a type of input widget to select one option from a group. Checkbox allows multiple selections but Radio Button allows only one selection at a time.

Example 1: Basic RadioButton

In this example, learn how to create a group of radio buttons for selecting Male, Female and Others. If you have any problem try Run Online button to see the code in action.

Step 1: Create Enum For Options

We will use enhanced enum to create the options for the radio buttons.

enum Gender {
  male("Male"),
  female("Female"),
  others("Others");

  // Members
  final String text;
  const Gender(this.text);
}
Step 2: Create State Variable

It’s time to create a state variable to store the selected option.

Gender? _selectedOption = Gender.male;
Step 3: Create Radio Buttons

Finally, create the radio buttons using the RadioListTile widget.

Column(
  // Radio buttons
  children: Gender.values
      .map((option) => RadioListTile<Gender>(
            title: Text(option.text),
            value: option,
            groupValue: _selectedOption,
            onChanged: (value) {
              setState(() {
                _selectedOption = value;
              });
            },
          ))
      .toList(),
)
Run Online

Example 2: Game Difficulty Selection

In this example, learn how to create a group of radio buttons for selecting the game difficulty level. If you have any problem try Run Online button to see the code in action.

Step 1: Create Enum For Options

We will use enhanced enum to create the options for the radio buttons.

enum Difficulty {
  easy("Easy"),
  medium("Medium"),
  hard("Hard");

  // Members
  final String text;
  const Difficulty(this.text);
}
Step 2: Create State Variable

It’s time to create a state variable to store the selected option.

Difficulty? _selectedDifficulty = Difficulty.easy;
Step 3: Create Radio Buttons

Finally, create the radio buttons using the RadioListTile widget.

Column(
  // Radio buttons
  children: Difficulty.values
      .map((option) => RadioListTile<Difficulty>(
            title: Text(option.text),
            value: option,
            groupValue: _selectedDifficulty,
            onChanged: (value) {
              setState(() {
                _selectedDifficulty = value;
              });
            },
          ))
      .toList(),
)
Run Online

Challenge

Create a quiz app with radio buttons to select the correct answer for each question.

Question: What is the capital of France?
Options:
- Paris
- London
- Berlin