flutter radiolisttile with label

How to use Flutter Radio buttons – guide with examples

Content

  • What is the Flutter Radio button?
  • Flutter Radio button properties
  • What is the radio button list?
  • How to use the Radio button in Flutter
  • How to use RadioListTile with Label in Flutter
  • How do I add text to my radio button? / How to use Radio with Label in Flutter?
  • Use ListTile with Radio button in Flutter
  • How to set default value among Radio buttons?
  • Can Radio buttons be unchecked?
  • Unselect Radio buttons in Flutter
  • How to reset Radio buttons in Flutter
  • Unselect Radio button option in Flutter
  • Can radio buttons have a value?
  • What type of values we can use with the Radio buttons in Flutter
  • Integer (int) Radio buttons value in Flutter
  • Boolean (bool) Radio buttons value in Flutter
  • String (String) values with Flutter Radio buttons
  • Double (double) values with Flutter Radio buttons
  • Enum values with Flutter Radio buttons
  • Custom object values with Flutter Radio buttons
  • How to create a List of multiple Radio buttons in Flutter with Listview
  • How to customize Flutter Radio button
  • Change Radio Button Colour
  • Customize Radio Button Labels
  • Appling Custom Styles to Flutter Radio buttons
  • How do I make one of my radio buttons required?
  • Flutter Radio Buttons validation
  • How to make a Flutter Radio button with Text and Icon
  • How to show hide the Flutter Radio buttons
  • How to evenly align the Flutter Radio buttons in a Row
  • How to increase the Flutter Radio widget size
  • What is an alternative to Flutter Radio buttons?
  • ToggleButtons as an alternative to the Flutter Radio buttons
  • Checkbox as an alternative to the Flutter Radio buttons

What is the Flutter Radio button?

The Flutter radio button is a graphical user interface (GUI) element that allows users to select a single option from a list of choices. It is a round button that represents a single item in a group of mutually exclusive options. When a radio button is selected, it displays a small dot or indicator inside it, indicating the user’s choice.

In simpler terms, imagine you have a list of options, like colours or sizes, and you want the user to choose only one option. Flutter radio button comes to the rescue by providing a visually appealing and interactive way to do that. It ensures that only one option can be selected at a time, making it useful for scenarios where you need the user to make a single choice from multiple possibilities.

Flutter Radio button properties

  • required int value – The value represented by this radio button.
  • required int? groupValue – The currently selected value for a group of radio buttons.
  • required void Function(int?)? onChanged – Called when the user selects this radio button.
  • MouseCursor? mouseCursor – The cursor for a mouse pointer when it enters or is hovering over the widget.
  • bool toggleable = false – Set to true if this radio button is allowed to be returned to an indeterminate state by selecting it again when selected.
  • Color? activeColor – The colour to use when this radio button is selected.
  • MaterialStateProperty? fillColor – The color that fills the radio button, in all MaterialStates.
  • Color? focusColor – The colour for the radio’s Material when it has the input focus.
  • Color? hoverColor – The colour for the radio’s Material when a pointer is hovering over it.
  • MaterialStateProperty? overlayColor – The colour for the radio’s Material.
  • double? splashRadius – The splash radius of the circular Material ink response.
  • MaterialTapTargetSize? materialTapTargetSize – Configures the minimum size of the tap target.
  • VisualDensity? visualDensity – Defines how compact the radio’s layout will be.
  • FocusNode? focusNode – An optional focus node to use as the focus node for this widget.
  • bool autofocus = false – True if this widget will be selected as the initial focus when no other node in its scope is currently focused.

What is the radio button list?

A radio button list, also known as a radio button group, is a user interface element that presents a set of options to the user, where only one option can be selected at a time. It is a way to provide mutually exclusive choices, allowing the user to make a single selection from a predefined list of options.

In a radio button list, each option is represented by a radio button accompanied by a label or text that describes the option. The radio buttons are typically displayed together vertically or horizontally, allowing the user to visually compare and select the desired option.

The main purpose of a radio button list is to provide a clear and intuitive interface for selecting one option from multiple choices. It ensures that only one option can be selected at a time, preventing ambiguous selections. The selected option is visually distinguished from the other options, providing immediate feedback to the user.

Radio button lists are commonly used in forms, surveys, quizzes, settings screens, and any situation where the user needs to choose a single option from a predefined list. They provide a straightforward and user-friendly way to capture the user’s selection and streamline the decision-making process.

In Flutter, you can create a radio button list by using widgets such as ListView, ListTile, and the Radio widget in combination with data binding and event handling. This allows you to build dynamic and interactive radio button lists that cater to your specific application requirements.

How to use the Radio button in Flutter

Here is a simple code example of the Flutter Radio button with a listTile.

int? selectedOption;

Column(
  mainAxisAlignment: MainAxisAlignment.start,
  children: <Widget>[
    ListTile(
      title: const Text('www.flutterassets.com'),
      leading: Radio(
        value: 1,
        groupValue: selectedOption,
        onChanged: (value) {
          setState(() {
            selectedOption = value;
            print("Button value: $value");
          });
        },
      ),
    ),
  ],
),
flutter radio button

In this code, a radio button is placed inside a ListTile widget, which displays a title and an optional leading widget. The radio button is assigned a value of 1 using the value property. The groupValue property is set to selectedOption, which is of type int? (nullable integer).

The onChanged property takes a callback function that is triggered when the radio button is selected. Inside the callback, setState is called to update the selectedOption variable with the newly selected value. Additionally, the print function is used to display the selected value in the console.

By using this code, you can display a single radio button with the text “www.flutterassets.com“. When the radio button is selected, the selectedOption variable is updated, and the selected value is printed to the console.

How to use RadioListTile with Label in Flutter

Adding a radio button with a label in Flutter is a common way to present a set of options to the user. Labels provide descriptive text that helps users understand the purpose of each radio button option. They add clarity and context to the choices, making it easier for users to make informed decisions.

The label is essential because it conveys the meaning and significance of each option. By including labels, users can quickly identify and differentiate between the available choices. The labels provide a clear indication of what each option represents, ensuring that users can select the most appropriate one for their needs or preferences.

Using the RadioListTile widget is beneficial because it combines the functionalities of a radio button and a ListTile in a convenient manner. The ListTile component acts as a container for the label text and the radio button, ensuring proper alignment and visual organization. Additionally, the ListTile widget allows for the inclusion of other elements such as trailing icons or subtitles, providing more versatility in designing the options.

Here’s a code example that demonstrates the usage of RadioListTile:

int? selectedOption;

Column(
  mainAxisAlignment: MainAxisAlignment.start,
  children: <Widget>[
    RadioListTile<int>(
      title: const Text('Option 1'),
      value: 1,
      groupValue: selectedOption,
      onChanged: (int? value) {
        setState(() {
          selectedOption = value;
          print("Selected Option: $selectedOption");
        });
      },
    ),
    RadioListTile<int>(
      title: const Text('Option 2'),
      value: 2,
      groupValue: selectedOption,
      onChanged: (int? value) {
        setState(() {
          selectedOption = value;
          print("Selected Option: $selectedOption");
        });
      },
    ),
  ],
),
flutter radiolisttile with label

In this code example, a Column widget is used to display a set of radio buttons with labels. Each RadioListTile represents an individual option. The title property is utilized to set the label text for each option. The value property denotes the value associated with the option, while the groupValue property holds the currently selected value.

When a user selects a radio button, the onChanged callback function is triggered, passing the selected value. Inside the callback, setState is used to update the selectedOption variable with the new value. Additionally, the selected option is printed to the console using the print function.

How do I add text to my radio button?

How to use Radio with Label in Flutter?

To add text to your radio buttons, you can make use of the Text widget alongside the Radio widget. Here’s an example of how you can add text to your radio buttons:

int selectedOption = 1; // Default selected option

Column(
  mainAxisAlignment: MainAxisAlignment.start,
  children: <Widget>[
    ListTile(
      title: const Text('Option 1'),
      leading: Radio<int>(
        value: 1,
        groupValue: selectedOption,
        onChanged: (int? value) {
          setState(() {
            selectedOption = value!;
            print("Selected Option: $selectedOption");
          });
        },
      ),
    ),
    ListTile(
      title: const Text('Option 2'),
      leading: Radio<int>(
        value: 2,
        groupValue: selectedOption,
        onChanged: (int? value) {
          setState(() {
            selectedOption = value!;
            print("Selected Option: $selectedOption");
          });
        },
      ),
    ),
  ],
),

In this example, the Text widget is used inside the ListTile widget as the title property. It displays the text associated with each radio button option. The leading property of the ListTile is set to the Radio widget, which represents the radio button itself.

You can modify the text inside the Text widget to customize the labels for each radio button option. By using the Text widget alongside the Radio widget, you can create radio buttons with descriptive text labels for better user understanding and interaction.

Use ListTile with Radio button in Flutter

You can use a ListTile instead of RadioListTile to add a radio button with a label in Flutter. While RadioListTile combines the functionalities of a radio button and a ListTile, ListTile itself provides a more basic tile structure without the built-in radio button functionality.

Here’s an example of using a ListTile with a radio button:

int? selectedOption;

Column(
  mainAxisAlignment: MainAxisAlignment.start,
  children: <Widget>[
    ListTile(
      title: const Text('Option 1'),
      leading: Radio<int>(
        value: 1,
        groupValue: selectedOption,
        onChanged: (int? value) {
          setState(() {
            selectedOption = value;
            print("Selected Option: $selectedOption");
          });
        },
      ),
    ),
    ListTile(
      title: const Text('Option 2'),
      leading: Radio<int>(
        value: 2,
        groupValue: selectedOption,
        onChanged: (int? value) {
          setState(() {
            selectedOption = value;
            print("Selected Option: $selectedOption");
          });
        },
      ),
    ),
  ],
),
flutter radio button with label

In this code example, ListTile is used to display the label text for each option. The leading property of ListTile is assigned a Radio widget, which provides the radio button functionality. The value property represents the value associated with the option, and the groupValue property holds the currently selected value.

When a radio button is selected, the onChanged callback function is triggered, passing the selected value. Inside the callback, setState is used to update the selectedOption variable with the new value. The selected option is also printed to the console.

How to set default value among Radio buttons?

To set a default value among radio buttons in Flutter, you need to initialize the selectedOption variable with the desired default value. Here’s an updated code example from above that demonstrates how to set a default value for the radio buttons:

int? selectedOption = 1; // Set the default value here

Column(
  mainAxisAlignment: MainAxisAlignment.start,
  children: <Widget>[
    ListTile(
      title: const Text('Option 1'),
      leading: Radio<int>(
        value: 1,
        groupValue: selectedOption,
        onChanged: (int? value) {
          setState(() {
            selectedOption = value;
            print("Selected Option: $selectedOption");
          });
        },
      ),
    ),
    ListTile(
      title: const Text('Option 2'),
      leading: Radio<int>(
        value: 2,
        groupValue: selectedOption,
        onChanged: (int? value) {
          setState(() {
            selectedOption = value;
            print("Selected Option: $selectedOption");
          });
        },
      ),
    ),
  ],
),
flutter radio button with label

In this code, the selectedOption variable is initialized with the default value of 1. By doing this, the first radio button will be selected by default when the widget is built.

You can modify the default value as per your requirements. For example, if you want the second option to be selected by default, you can change selectedOption = 2.

By setting the selectedOption variable to the desired default value, you ensure that the corresponding radio button is initially selected when the widget is displayed.

Can Radio buttons be unchecked?

In Flutter, radio buttons cannot be unchecked by the user within a group of radio buttons. This behaviour ensures that only one option is selected at a time, adhering to the concept of mutually exclusive choices. Once a radio button is selected, it remains selected until another option is chosen.

Unselect Radio buttons in Flutter

If you need to allow for an unchecked state or the ability to unselect a radio button, there are a couple of approaches you can take. One way is to include an additional radio button option that represents an “unselect” or “none” choice. By adding this option, the user can explicitly indicate no selection. Another approach is to incorporate a separate control, such as a “Clear” button, that triggers a reset action, setting the selected option to null or an initial default value.

How to reset Radio buttons in Flutter

Here’s an example code snippet that demonstrates how you can reset the selected radio button in Flutter using a “Clear” button:

int? selectedOption;

Column(
  mainAxisAlignment: MainAxisAlignment.start,
  children: <Widget>[
    ListTile(
      title: const Text('Option 1'),
      leading: Radio<int>(
        value: 1,
        groupValue: selectedOption,
        onChanged: (int? value) {
          setState(() {
            selectedOption = value;
            print("Selected Option: $selectedOption");
          });
        },
      ),
    ),
    ListTile(
      title: const Text('Option 2'),
      leading: Radio<int>(
        value: 2,
        groupValue: selectedOption,
        onChanged: (int? value) {
          setState(() {
            selectedOption = value;
            print("Selected Option: $selectedOption");
          });
        },
      ),
    ),
    ElevatedButton(
      onPressed: () {
        setState(() {
          selectedOption = null; // Reset the selected option
          print("Selected Option: $selectedOption");
        });
      },
      child: Text("Clear"),
    ),
  ],
),
reset flutter radio buttons

In this code, the selectedOption variable keeps track of the currently selected radio button. When a radio button is selected, it updates the selectedOption with the corresponding value. To reset the selection, the “Clear” button triggers the onPressed callback, which sets the selectedOption to null. This effectively clears the selected option.

By using the setState function, the widget is rebuilt, reflecting the changes and updating the UI accordingly. You can customize the “Clear” button’s appearance and behaviour based on your app’s design and requirements.

Unselect Radio button option in Flutter

To add an “unselect” or “none” choice to the radio buttons without using a reset button, you can modify the above code to include an additional radio button option. Here’s an example:

int? selectedOption = -1; // Set the default value here

  // Define a constant value for the "unselect" choice
  int unselectValue = -1;

Column(
  mainAxisAlignment: MainAxisAlignment.start,
  children: <Widget>[
    ListTile(
      title: const Text('None'), // "Unselect" or "None" choice
      leading: Radio<int>(
        value: unselectValue, // Use the special value to indicate "None"
        groupValue: selectedOption,
        onChanged: (int? value) {
          setState(() {
            selectedOption = value;
            print("Selected Option: $selectedOption");
          });
        },
      ),
    ),
    ListTile(
      title: const Text('Option 1'),
      leading: Radio<int>(
        value: 1,
        groupValue: selectedOption,
        onChanged: (int? value) {
          setState(() {
            selectedOption = value;
            print("Selected Option: $selectedOption");
          });
        },
      ),
    ),
    ListTile(
      title: const Text('Option 2'),
      leading: Radio<int>(
        value: 2,
        groupValue: selectedOption,
        onChanged: (int? value) {
          setState(() {
            selectedOption = value;
            print("Selected Option: $selectedOption");
          });
        },
      ),
    ),
  ],
),
unselect flutter radio buttons

In this updated code, we introduced a constant unselectValue with a unique value (-1 in this case) to represent the “unselect” or “none” choice. Instead of using null, we assign this special value to the radio button representing the “unselect” option. When this radio button is selected, it sets the selectedOption to the unselectValue.

By using a distinct value that is not present in the valid options, we can effectively indicate the “unselect” or “none” choice within the radio button group.

Can radio buttons have a value?

Yes, in Flutter, radio buttons can have a value associated with them. The value of a radio button represents the selected option within a group of radio buttons. When a radio button is selected, its corresponding value is assigned to the variable that represents the selected option.

By assigning values to radio buttons, you can differentiate and process different options based on their selected values. For example, you can perform specific actions or store the selected value in a variable for further use.

Here’s an example code snippet that demonstrates the usage of values with radio buttons:

int? selectedOption;

Column(
  mainAxisAlignment: MainAxisAlignment.start,
  children: <Widget>[
    ListTile(
      title: const Text('Option 1'),
      leading: Radio<int>(
        value: 1,  // Assign a value to the radio button
        groupValue: selectedOption,
        onChanged: (int? value) {
          setState(() {
            selectedOption = value;
            print("Selected Option: $selectedOption");
          });
        },
      ),
    ),
    ListTile(
      title: const Text('Option 2'),
      leading: Radio<int>(
        value: 2,  // Assign a different value to the radio button
        groupValue: selectedOption,
        onChanged: (int? value) {
          setState(() {
            selectedOption = value;
            print("Selected Option: $selectedOption");
          });
        },
      ),
    ),
  ],
),

In this example, each radio button is assigned a unique integer value (1 and 2). When a radio button is selected, its corresponding value is assigned to the selectedOption variable. You can access and utilize this value as needed in your code.

Assigning values to radio buttons allows you to handle different options based on their associated values, enabling you to perform specific logic or actions based on the selected value within the radio button group.

What type of values we can use with the Radio buttons in Flutter

In Flutter, radio buttons can have values of various types,

  1. Integer (int): Radio buttons can be assigned integer values, useful for associating numerical options with specific integer values.
  2. Boolean (bool): Radio buttons can represent boolean choices by assigning true and false as values.
  3. String (String): String values can be used with radio buttons, allowing you to associate textual options with each radio button.
  4. Double (double): Radio buttons can have double values, enabling you to assign fractional or decimal values to represent different options.
  5. Enum: Enums can serve as the value type for radio buttons. This allows you to define a set of named values and associate them with specific behaviours or data.
  6. Custom Object: You can use custom objects as the value type for radio buttons, providing flexibility to associate complex data structures with each option.

Integer (int) Radio buttons value in Flutter

Here’s a simple example demonstrating the usage of integer values with Flutter radio buttons:

int selectedOption = 1; // Default selected option

Column(
  mainAxisAlignment: MainAxisAlignment.start,
  children: <Widget>[
    ListTile(
      title: const Text('Option 1'),
      leading: Radio<int>(
        value: 1,
        groupValue: selectedOption,
        onChanged: (int? value) {
          setState(() {
            selectedOption = value!;
            print("Selected Option: $selectedOption");
          });
        },
      ),
    ),
    ListTile(
      title: const Text('Option 2'),
      leading: Radio<int>(
        value: 2,
        groupValue: selectedOption,
        onChanged: (int? value) {
          setState(() {
            selectedOption = value!;
            print("Selected Option: $selectedOption");
          });
        },
      ),
    ),
  ],
),
flutter integer value radio button

In this example, we have two radio button options represented by Option 1 and Option 2. The selected option is tracked by the selectedOption variable of type int. By default, Option 1 is initially selected because selectedOption is set to 1.

The Radio<int> widget is used for each radio button. The value property represents the integer value associated with the respective option. The groupValue property is set to selectedOption, which determines the currently selected radio button based on the value of selectedOption. The onChanged callback is triggered when a radio button is selected, updating the selectedOption and printing the selected value.

Boolean (bool) Radio buttons value in Flutter

Here’s a simple example demonstrating the usage of boolean values with Flutter radio buttons:

bool selectedOption = true; // Default selected option

Column(
  mainAxisAlignment: MainAxisAlignment.start,
  children: <Widget>[
    ListTile(
      title: const Text('Option 1'),
      leading: Radio<bool>(
        value: true,
        groupValue: selectedOption,
        onChanged: (bool? value) {
          setState(() {
            selectedOption = value!;
            print("Selected Option: $selectedOption");
          });
        },
      ),
    ),
    ListTile(
      title: const Text('Option 2'),
      leading: Radio<bool>(
        value: false,
        groupValue: selectedOption,
        onChanged: (bool? value) {
          setState(() {
            selectedOption = value!;
            print("Selected Option: $selectedOption");
          });
        },
      ),
    ),
  ],
),
flutter boolean value radio button

In this example, we have two radio button options represented by Option 1 and Option 2. The selected option is tracked by the selectedOption variable of type bool. By default, Option 1 is initially selected because selectedOption is set to true.

The Radio<bool> widget is used for each radio button. The value property represents the boolean value associated with the respective option. The groupValue property is set to selectedOption, which determines the currently selected radio button based on the value of selectedOption. The onChanged callback is triggered when a radio button is selected, updating the selectedOption and printing the selected value.

String (String) values with Flutter Radio buttons

Here’s a simple example demonstrating the usage of string values with Flutter radio buttons:

String selectedOption = 'Option 1'; // Default selected option

Column(
  mainAxisAlignment: MainAxisAlignment.start,
  children: <Widget>[
    ListTile(
      title: const Text('Option 1'),
      leading: Radio<String>(
        value: 'Option 1',
        groupValue: selectedOption,
        onChanged: (String? value) {
          setState(() {
            selectedOption = value!;
            print("Selected Option: $selectedOption");
          });
        },
      ),
    ),
    ListTile(
      title: const Text('Option 2'),
      leading: Radio<String>(
        value: 'Option 2',
        groupValue: selectedOption,
        onChanged: (String? value) {
          setState(() {
            selectedOption = value!;
            print("Selected Option: $selectedOption");
          });
        },
      ),
    ),
  ],
),
flutter String value radio button

In this example, we have two radio button options represented by Option 1 and Option 2. The selected option is tracked by the selectedOption variable of type String. By default, Option 1 is initially selected because selectedOption is set to 'Option 1'.

The Radio<String> widget is used for each radio button. The value property represents the string value associated with the respective option. The groupValue property is set to selectedOption, which determines the currently selected radio button based on the value of selectedOption. The onChanged callback is triggered when a radio button is selected, updating the selectedOption and printing the selected value.

Double (double) values with Flutter Radio buttons

Here’s a simple example demonstrating the usage of double values with Flutter radio buttons:

double selectedOption = 1.0; // Default selected option

Column(
  mainAxisAlignment: MainAxisAlignment.start,
  children: <Widget>[
    ListTile(
      title: const Text('Option 1'),
      leading: Radio<double>(
        value: 1.0,
        groupValue: selectedOption,
        onChanged: (double? value) {
          setState(() {
            selectedOption = value!;
            print("Selected Option: $selectedOption");
          });
        },
      ),
    ),
    ListTile(
      title: const Text('Option 2'),
      leading: Radio<double>(
        value: 2.5,
        groupValue: selectedOption,
        onChanged: (double? value) {
          setState(() {
            selectedOption = value!;
            print("Selected Option: $selectedOption");
          });
        },
      ),
    ),
  ],
),
flutter double value radio button

In this example, we have two radio button options represented by Option 1 and Option 2. The selected option is tracked by the selectedOption variable of type double. By default, Option 1 is initially selected because selectedOption is set to 1.0.

The Radio<double> widget is used for each radio button. The value property represents the double value associated with the respective option. The groupValue property is set to selectedOption, which determines the currently selected radio button based on the value of selectedOption. The onChanged callback is triggered when a radio button is selected, updating the selectedOption and printing the selected value.

Enum values with Flutter Radio buttons

Here’s a simple example demonstrating the usage of enum values with Flutter radio buttons:

import 'package:flutter/material.dart';

void main() {
runApp(MyApp());
}

class MyApp extends StatelessWidget {

@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(),
);
}
}

class MyHomePage extends StatefulWidget {

@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage>{

Option selectedOption = Option.option1; // Default selected option

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('flutterassets.com'),
),
body: Column(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
ListTile(
title: const Text('Option 1'),
leading: Radio<Option>(
value: Option.option1,
groupValue: selectedOption,
onChanged: (Option? value) {
setState(() {
selectedOption = value!;
print("Selected Option: $selectedOption");
});
},
),
),
ListTile(
title: const Text('Option 2'),
leading: Radio<Option>(
value: Option.option2,
groupValue: selectedOption,
onChanged: (Option? value) {
setState(() {
selectedOption = value!;
print("Selected Option: $selectedOption");
});
},
),
),
],
),
);
}
}

enum Option {
option1,
option2,
}
flutter enum value radio button

In this example, we have an enum Option with two values: option1 and option2. The selected option is tracked by the selectedOption variable of type Option. By default, Option 1 is initially selected because selectedOption is set to Option.option1.

The Radio<Option> widget is used for each radio button. The value property represents the enum value associated with the respective option. The groupValue property is set to selectedOption, which determines the currently selected radio button based on the value of selectedOption. The onChanged callback is triggered when a radio button is selected, updating the selectedOption and printing the selected value.

Custom object values with Flutter Radio buttons

Here’s a simple example demonstrating the usage of a custom object as values with Flutter radio buttons:

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage>{

  Option selectedOption = Option('Option 1', 1); // Default selected option

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('flutterassets.com'),
      ),
      body: Column(
        mainAxisAlignment: MainAxisAlignment.start,
        children: <Widget>[
          ListTile(
            title: const Text('Option 1'),
            leading: Radio<Option>(
              value: Option('Option 1', 1),
              groupValue: selectedOption,
              onChanged: (Option? value) {
                setState(() {
                  selectedOption = value!;
                  print("Selected Option: ${selectedOption.label}");
                });
              },
            ),
          ),
          ListTile(
            title: const Text('Option 2'),
            leading: Radio<Option>(
              value: Option('Option 2', 2),
              groupValue: selectedOption,
              onChanged: (Option? value) {
                setState(() {
                  selectedOption = value!;
                  print("Selected Option: ${selectedOption.label}");
                });
              },
            ),
          ),
        ],
      ),
    );
  }
}

class Option {
  final String label;
  final int value;

  Option(this.label, this.value);

  @override
  bool operator ==(Object other) =>
      identical(this, other) ||
          other is Option &&
              runtimeType == other.runtimeType &&
              label == other.label &&
              value == other.value;

  @override
  int get hashCode => label.hashCode ^ value.hashCode;
}
flutter custom object value radio button

In this example, we use a custom object (Option) as values with Flutter radio buttons. The Option class represents each radio button option and has a label of type String and a value of type int.

In this example, the Option class also overrides the == operator and hashCode to ensure correct equality comparisons between different instances of the class. This is important because the Radio widget relies on the equality check to determine the selected option.

The selectedOption variable holds the currently selected Option object. The Radio<Option> widgets are used for each radio button, with the value property representing an instance of the Option class associated with each option. The groupValue property is set to selectedOption ensuring that the correct radio button is selected based on the equality comparison.

When a radio button is selected, the onChanged callback is triggered, updating the selectedOption and printing the selected label.

How to create a List of multiple Radio buttons in Flutter with Listview

To create a list of radio buttons in Flutter, you can make use of a ListView widget and iterate over your data to generate the radio button options dynamically. Here’s a simple example that demonstrates how to create a list of radio buttons:

int selectedOption = 1; // Default selected option

List<String> options = ['Option 1', 'Option 2', 'Option 3'];

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('flutterassets.com'),
),
body: ListView.builder(
itemCount: options.length,
itemBuilder: (BuildContext context, int index) {
return ListTile(
title: Text(options[index]),
leading: Radio<int>(
value: index + 1,
groupValue: selectedOption,
onChanged: (int? value) {
setState(() {
selectedOption = value!;
print("Selected Option: $selectedOption");
});
},
),
);
},
),
);
}

In this example, we have a List<String> named options that holds the radio button options. Inside the ListView.builder, we specify the itemCount to be the length of the options list. The itemBuilder function is called for each item in the list, where we create a ListTile widget.

For each ListTile, we set the title property to display the option text from the options list using Text. The leading property is set to a Radio<int> widget. We assign a unique value (in this case, index + 1) to each radio button using the index of the item. The groupValue is set to selectedOption to determine which radio button is currently selected. The onChanged callback is triggered when a radio button is selected, updating the selectedOption and printing the selected value.

By using a ListView.builder and iterating over your data, you can create a dynamic list of radio buttons with customizable options. This approach allows you to easily scale and manage large sets of radio button options in your Flutter application.

How to customize Flutter Radio button

To customize Flutter radio buttons, you can modify their appearance and behaviour using various techniques. Here are some common ways to customize radio buttons in Flutter:

Change Radio Button Colour

To customize the colour of the Flutter radio button, you can use the activeColor, fillColor and also the splashRadius(partially colour-related) property of the Radio widget. Here’s an example of how to use these properties to customize the radio button:

int? selectedOption;

Column(
  mainAxisAlignment: MainAxisAlignment.start,
  children: <Widget>[
    ListTile(
      title: const Text('Option 1'),
      leading: Radio<int>(
        value: 1,
        groupValue: selectedOption,
        activeColor: Colors.red, // Change the active radio button color here
        fillColor: MaterialStateProperty.all(Colors.red), // Change the fill color when selected
        splashRadius: 20, // Change the splash radius when clicked
        onChanged: (int? value) {
          setState(() {
            selectedOption = value!;
            print("Selected Option: $selectedOption");
          });
        },
      ),
    ),
    ListTile(
      title: const Text('Option 2'),
      leading: Radio<int>(
        value: 2,
        groupValue: selectedOption,
        activeColor: Colors.blue, // Change the active radio button color here
        fillColor: MaterialStateProperty.all(Colors.blue), // Change the fill color when selected
        splashRadius: 25, // Change the splash radius when clicked
        onChanged: (int? value) {
          setState(() {
            selectedOption = value!;
            print("Selected Option: $selectedOption");
          });
        },
      ),
    ),
  ],
),
customize colours flutter radio buttons

In this code example, the activeColor property is used to change the colour of the radio button when it is selected. You can set it to any desired Color. The fillColor property, which is of type MaterialStateProperty<Color>, allows you to specify a fill colour for the radio button when it is selected. You can pass a MaterialStateProperty.all() constructor with the desired Color value.

Additionally, the splashRadius property determines the radius of the splash effect when the radio button is clicked. You can adjust this value to change the size of the splash effect.

Customize Radio Button Labels

To customize the labels of Flutter radio buttons, you can modify the text appearance, alignment, and style within the ListTile widget. Here’s an example of how to customize the radio button labels:

int selectedOption = 1; // Default selected option

Column(
  mainAxisAlignment: MainAxisAlignment.start,
  children: <Widget>[
    ListTile(
      title: Text(
        'Option 1',
        style: TextStyle(
          fontSize: 26, // Change the font size of the label
          fontWeight: FontWeight.bold, // Change the font weight of the label
          color: Colors.black, // Change the text color of the label
        ),
      ),
      leading: Radio<int>(
        value: 1,
        groupValue: selectedOption,
        onChanged: (int? value) {
          setState(() {
            selectedOption = value!;
            print("Selected Option: $selectedOption");
          });
        },
      ),
    ),
    ListTile(
      title: Text(
        'Option 2',
        style: TextStyle(
          fontSize: 26, // Change the font size of the label
          fontWeight: FontWeight.bold, // Change the font weight of the label
          color: Colors.black, // Change the text color of the label
        ),
      ),
      leading: Radio<int>(
        value: 2,
        groupValue: selectedOption,
        onChanged: (int? value) {
          setState(() {
            selectedOption = value!;
            print("Selected Option: $selectedOption");
          });
        },
      ),
    ),
  ],
),
customize label flutter radio buttons

In this code example, the title property of each ListTile is set to a Text widget. You can customize the appearance of the label by applying different styles to the TextStyle of the Text widget. The TextStyle allows you to change properties such as fontSize, fontWeight, and color. Modify these properties to adjust the label’s font size, weight, and colour according to your preferences.

Appling Custom Styles to Flutter Radio buttons

To apply custom styles to Flutter radio buttons, you can wrap the Radio widget with other widgets like Container or InkWell. This allows you to define custom styles, such as background colour, border, padding, or other visual effects. Here’s an example of how to apply custom styles to radio buttons:

int? selectedOption = 1;

Column(
  mainAxisAlignment: MainAxisAlignment.start,
  children: <Widget>[
    InkWell(
      onTap: () {
        setState(() {
          selectedOption = 1;
          print("Selected Option: $selectedOption");
        });
      },
      child: Container(
        padding: EdgeInsets.all(10), // Add padding around the radio button
        decoration: BoxDecoration(
          color: Colors.grey, // Change the background color
          borderRadius: BorderRadius.circular(36), // Add rounded corners
        ),
        child: Row(
          children: [
            Radio<int>(
              value: 1,
              groupValue: selectedOption,
              onChanged: (int? value) {
                setState(() {
                  selectedOption = value!;
                  print("Selected Option: $selectedOption");
                });
              },
            ),
            Text(
              'Option 1',
              style: TextStyle(
                fontSize: 16,
                color: Colors.white,
              ),
            ),
          ],
        ),
      ),
    ),
    InkWell(
      onTap: () {
        setState(() {
          selectedOption = 2;
          print("Selected Option: $selectedOption");
        });
      },
      child: Container(
        padding: EdgeInsets.all(10),
        decoration: BoxDecoration(
          color: Colors.green,
          borderRadius: BorderRadius.circular(36),
        ),
        child: Row(
          children: [
            Radio<int>(
              value: 2,
              groupValue: selectedOption,
              onChanged: (int? value) {
                setState(() {
                  selectedOption = value!;
                  print("Selected Option: $selectedOption");
                });
              },
            ),
            Text(
              'Option 2',
              style: TextStyle(
                fontSize: 16,
                color: Colors.white,
              ),
            ),
          ],
        ),
      ),
    ),
  ],
),
customize style flutter radio buttons

In this code example, the radio buttons are wrapped with InkWell widgets, which provide the tap gesture functionality. The InkWell widgets are then wrapped with Container widgets to apply custom styles. You can customize the Container properties, such as color, borderRadius, and padding, to achieve the desired visual effect.

Inside the Container, a Row widget is used to place the radio button and label side by side. The Text widget represents the label of the radio button, and you can customize its appearance using the TextStyle.

How do I make one of my radio buttons required?

Flutter Radio Buttons validation

To make one of your Flutter radio buttons required, you can use form validation. Form validation ensures that the user has selected a radio button option before proceeding.

First, create a Form widget and assign a GlobalKey<FormState> to it. This key allows you to access the form’s state and perform validation. Inside the Form, create a Column and add RadioListTile widgets for each radio button option. Each RadioListTile should have a unique value and share the same groupValue, which is assigned to the selectedOption variable.

Next, create an ElevatedButton that triggers the form validation when pressed. In the onPressed callback, access the form’s state using the FormState from the GlobalKey. Use the validate() method to check if the form is valid. If the validation fails (no option is selected), set the showError flag to true. Otherwise, set it to false, indicating a successful validation.

To provide visual feedback when the form is submitted without selecting an option, conditionally render a Text widget below the ElevatedButton based on the value of showError. If showError is true, display the error message “Please select an option” in red.

Here’s the updated code snippet based on your provided example:

String? selectedOption;
  GlobalKey<FormState> _formKey = GlobalKey<FormState>();
  bool showError = false;

Form(
  key: _formKey,
  child: Column(
    children: [
      RadioListTile<String>(
        title: Text('Option 1'),
        value: 'Option 1',
        groupValue: selectedOption,
        onChanged: (value) {
          setState(() {
            selectedOption = value;
            showError = false;
          });
        },
      ),
      RadioListTile<String>(
        title: Text('Option 2'),
        value: 'Option 2',
        groupValue: selectedOption,
        onChanged: (value) {
          setState(() {
            selectedOption = value;
            showError = false;
          });
        },
      ),
      ElevatedButton(
        onPressed: () {
          setState(() {
            if (selectedOption == null) {
              showError = true;
            } else {
              showError = false;
              // Validation successful, proceed with form submission
              print('Selected Option: $selectedOption');
            }
          });
        },
        child: Text('Submit'),
      ),
      if (showError)
        Text(
          'Please select an option',
          style: TextStyle(color: Colors.red),
        ),
    ],
  ),
)
flutter radio button required validation

With this implementation, the Form widget ensures that the user selects a radio button option before proceeding. When the form is submitted by pressing the “Submit” button, the validation is performed. If no option is selected, the error message will be displayed. Otherwise, the selected option will be printed, indicating a successful validation.

How to make a Flutter Radio button with Text and Icon

To make a Flutter radio button display text with an icon, you can use the ListTile widget. The ListTile allows you to create a layout with an icon and a title.

Here’s an example of how to create a radio button with text and an icon:

String? selectedOption;

Column(
  children: [
    ListTile(
      leading: Icon(Icons.home), // Replace with your desired icon
      title: Text('Option 1'),
      trailing: Radio<String>(
        value: 'Option 1',
        groupValue: selectedOption,
        onChanged: (value) {
          setState(() {
            selectedOption = value;
          });
        },
      ),
    ),
    ListTile(
      leading: Icon(Icons.work), // Replace with your desired icon
      title: Text('Option 2'),
      trailing: Radio<String>(
        value: 'Option 2',
        groupValue: selectedOption,
        onChanged: (value) {
          setState(() {
            selectedOption = value;
          });
        },
      ),
    ),
  ],
),
flutter radio button with text and icon

In this example, we use the ListTile widget to create each radio button option. The leading property is used to specify the icon you want to display. You can replace the Icon(Icons.XXX) with the desired icon from the Flutter Icons class or use a custom icon. The title property is used to specify the text label for the radio button option.

The trailing property is where we place the Radio widget. The Radio widget represents the radio button itself. The value property is set to the respective option value, and the groupValue property is set to the selectedOption variable. The onChanged callback updates the selectedOption variable when a radio button is selected.

How to show hide the Flutter Radio buttons

To show/hide Flutter radio buttons based on user interaction, you can use a combination of the Visibility widget and an ElevatedButton. The Visibility widget allows you to control the visibility of its child widget, while the ElevatedButton triggers the hide/show functionality.

int? selectedOption;
  bool showRadioButtons = true; // Initially show the radio buttons

Container(
  padding: EdgeInsets.all(10),
  child: Column(
    crossAxisAlignment: CrossAxisAlignment.start,
    children: [
      ElevatedButton(
        onPressed: () {
          setState(() {
            showRadioButtons = !showRadioButtons; // Toggle the visibility
          });
        },
        child: Text(showRadioButtons ? 'Hide Radio Buttons' : 'Show Radio Buttons'),
      ),
      Visibility(
        visible: showRadioButtons,
        child: Column(
          children: [
            // Your radio button code here
            ListTile(
              title: Text('Option 1'),
              leading: Radio<int>(
                value: 1,
                groupValue: selectedOption,
                onChanged: (value) {
                  setState(() {
                    selectedOption = value;
                  });
                },
              ),
            ),
            ListTile(
              title: Text('Option 2'),
              leading: Radio<int>(
                value: 2,
                groupValue: selectedOption,
                onChanged: (value) {
                  setState(() {
                    selectedOption = value;
                  });
                },
              ),
            ),
          ],
        ),
      ),
    ],
  ),
),

In this code, we have a showRadioButtons boolean variable that determines whether the radio buttons should be shown or hidden. Initially, it’s set to true, so the radio buttons are shown.

We wrap the radio button code with the Visibility widget and set its visible property to the value of showRadioButtons. This ensures that the radio buttons are only visible when showRadioButtons is true.

Above the radio buttons, we have an ElevatedButton. When this button is pressed, we toggle the value of showRadioButtons using setState, effectively hiding or showing the radio buttons based on the updated value.

How to evenly align the Flutter Radio buttons in a Row

To evenly align the Flutter radio buttons in a row, you can use the Expanded widget along with the mainAxisAlignment property. Here’s the modified code:

Column(
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
Expanded(
child: Row(
children: [
Radio(
value: 1, groupValue: 'null', onChanged: (index) {}),
Expanded(
child: Text('Radio button 1'),
)
],
),
flex: 1,
),
Expanded(
child: Row(
children: [
Radio(
value: 1, groupValue: 'null', onChanged: (index) {}),
Expanded(child: Text('Radio 2'))
],
),
flex: 1,
),
Expanded(
child: Row(
children: [
Radio(
value: 1, groupValue: 'null', onChanged: (index) {}),
Expanded(child: Text('3'))
],
),
flex: 1,
),
Expanded(
child: Row(
children: [
Radio(
value: 1, groupValue: 'null', onChanged: (index) {}),
Expanded(child: Text('Radio button 4'))
],
),
flex: 1,
),
],
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
Expanded(
flex: 1,
child: Row(
children: [
Radio(
value: 1, groupValue: 'null', onChanged: (index) {}),
Expanded(child: Text('Radio button 5'))
],
),
),
Expanded(
flex: 1,
child: Row(
children: [
Radio(
value: 1, groupValue: 'null', onChanged: (index) {}),
Expanded(child: Text('Radio 6'))
],
),
),
Expanded(
flex: 1,
child: Row(
children: [
Radio(
value: 1, groupValue: 'null', onChanged: (index) {}),
Expanded(
child: Text('Radio button 7'),
)
],
),
),
],
),
],
),
flutter radio button row alignment

In the above code, the Expanded widget is used to distribute the available space evenly among the radio buttons in each row. The mainAxisAlignment property of the outer Row widget is set to spaceEvenly, which evenly spaces the radio buttons horizontally. Additionally, the flex property of the Expanded widget is set to control the relative widths of the radio buttons.

How to increase the Flutter Radio widget size

To increase the size of the Flutter Radio Widget, you can use the Transform.scale widget to scale up the size of the radio button. Here’s an example:

Transform.scale(
scale: 2, // Increase the scale factor to increase the size
child: Radio<int>(
value: 1,
groupValue: selectedOption,
onChanged: (value) {
setState(() {
selectedOption = value;
});
},
),
)
flutter radio button scale

In the code above, the Transform.scale widget wraps the Radio widget. By adjusting the scale property, you can increase or decrease the size of the radio button. A scale factor of 1.0 represents the original size, while a scale factor greater than 1.0 increases the size, and a scale factor less than 1.0 decreases the size.

You can place the Transform.scale widget anywhere in your widget tree where you want to increase the size of the radio button. Adjust the scale property according to your desired size preference.

What is an alternative to Flutter Radio buttons?

Here are two Flutter widgets which can be used as alternatives to Flutter Radio Buttons:

  1. ToggleButton: The ToggleButton widget allows users to select multiple options from a group of buttons. Each button represents a specific option, and the user can toggle the state of the buttons to select or deselect options. This is useful when you want to allow users to choose multiple options simultaneously.
  2. Checkbox: The Checkbox widget provides a simple way to present a binary choice to the user. It displays a box that can be checked or unchecked to represent the selection state. Users can toggle the checkbox to select or deselect the option. This is useful when you want to present a simple yes/no or true/false choice.

ToggleButtons as an alternative to the Flutter Radio buttons

Here’s an example of using ToggleButton as an alternative to radio buttons in Flutter where only one option can be selected:

List<bool> toggleButtonValues = [false, false, false];
List<String> options = ['Option 1', 'Option 2', 'Option 3'];

Container(
  padding: EdgeInsets.all(10),
  child: ToggleButtons(
    isSelected: toggleButtonValues,
    onPressed: (int index) {
      setState(() {
        for (int i = 0; i < toggleButtonValues.length; i++) {
          toggleButtonValues[i] = false;
        }
        toggleButtonValues[index] = true;
      });
    },
    children: options.map((option) {
      int index = options.indexOf(option);
      return Text(option);
    }).toList(),
  ),
)
flutter togglebuttons as radio buttons

In this example, we create a ToggleButton widget and provide a list of ToggleButton children based on the available options. Each child represents a specific option and has its own value and text. The toggleButtonValues list is used to track the selection state of each toggle button.

When a toggle button is pressed, we update the toggleButtonValues list to ensure that only one toggle button is selected at a time. We achieve this by setting all the values to false and then setting the value of the pressed button to true.

The ToggleButton widget can be customized with different styles, such as changing the background color or text color, to match your app’s design.

Checkbox as an alternative to the Flutter Radio buttons

Here’s an example of using Checkbox as an alternative to radio buttons in Flutter where only one option can be selected:

import 'package:flutter/material.dart';

void main() {
runApp(MyApp());
}

class MyApp extends StatelessWidget {

@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(),
);
}
}

class MyHomePage extends StatefulWidget {

@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage>{

List<Option> options = [
Option('Option 1', false),
Option('Option 2', false),
Option('Option 3', false),
];

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('flutterassets.com'),
),
body: Container(
padding: EdgeInsets.all(10),
child: Column(
children: options.map((option) {
return CheckboxListTile(
title: Text(option.label),
value: option.isSelected,
onChanged: (bool? value) {
setState(() {
for (Option o in options) {
o.isSelected = false;
}
option.isSelected = value!;
});
},
);
}).toList(),
)
)
);
}
}

class Option {
final String label;
bool isSelected;

Option(this.label, this.isSelected);
}
flutter checkbox as radio buttons

In this example, we define a Option class that represents each checkbox option. It contains a label for the option and a isSelected flag to track whether the checkbox is selected or not.

We create a list of Option objects, each representing a checkbox option, and initialize their isSelected values to false.

We then use the Column widget to display a list of CheckboxListTile widgets. The CheckboxListTile widget provides a checkbox with a label. We map each Option object to a CheckboxListTile widget, setting the title to the option label and the value to the isSelected flag of the corresponding Option object.

The onChanged callback is triggered when a checkbox is toggled. Inside the callback, we iterate over all the Option objects and set their isSelected flags to false, ensuring that only one checkbox can be selected. Then we set the isSelected flag of the current Option object to the new value.