flutterradio-buttonradiobuttonlist

Method to create two separate sets of Radio button in a single body property


My aim is to have two different sets of Radio buttons in a single page of my app. I have written the following code, which is erroneous now and needs help with.

I searched the different sources in internet, which used String values as value to the groupValue of Radio button, which worked for them but does not work for me. Now, perhaps (assuming it was different previously) it changed and allows only integer values.

What I'd like:

I was looking if I could use enum values, or String values (last priority List of int values) as values to the value and groupValue properties of Radio button so that my code could be more organized and easy to manipulate. I currently use hardcoded values for the value property, so if I look to add a new set of Radio buttons to the page, I'll have to use different numbers, other than those used in the previous set of Radio buttons. I'm looking to overcome this.

In the following code, I also tried using int list variable as values to value property of Radio button, but that failed, results in error.

How can I get the above expectation in the code? Please help. Thank you.

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  final String title;

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

List<int> radioSet01 = [
  1,
  2,
];

class _MyHomePageState extends State<MyHomePage> {
  int currentRadioSet01Option = radioSet01[0];
  int _groupRadioSet01Value = 1;
  int _groupRadioSet02Value = 3;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        title: Text(widget.title),
      ),
      body: const Column(
        children: [
          Center(
            child: Text("First Set of Radio Buttons"),
          ),
          Row(
            children: [
              Radio(
                value: 1,
                groupValue: _groupRadioSet01Value,
                onChanged: (value) {
                  setState(() {
                    _groupRadioSet01Value = value!;
                  });
                },
              ),
              Text("First option of Set 1"),
            ],
          ),
          Row(
            children: [
              Radio(
                value: 2,
                groupValue: _groupRadioSet01Value,
                onChanged: (value) {
                  setState(() {
                    _groupRadioSet01Value = value!;
                  });
                },
              ),
              Text("Second option of Set 1"),
            ],
          ),
          Center(
            child: Text("Second Set of Radio Buttons"),
          ),
          Row(
            children: [
              Radio(
                value: 3,
                groupValue: _groupRadioSet02Value,
                onChanged: (value) {
                  setState(() {
                    _groupRadioSet02Value = value!;
                  });
                },
              ),
              Text("First option of Set 2"),
            ],
          ),
          Row(
            children: [
              Radio(
                value: 4,
                groupValue: _groupRadioSet02Value,
                onChanged: (value) {
                  setState(() {
                    _groupRadioSet02Value = value!;
                  });
                },
              ),
              Text("Second option of Set 2"),
            ],
          ),
        ],
      ),
    );
  }
}

Solution

  •     import 'package:flutter/material.dart';
    
    // Define enums for the radio button groups
    enum RadioGroup1 { option1, option2 }
    enum RadioGroup2 { option1, option2 }
    
    void main() {
      runApp(MyApp());
    }
    
    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          home: RadioButtonExample(),
        );
      }
    }
    
    class RadioButtonExample extends StatefulWidget {
      @override
      _RadioButtonExampleState createState() => _RadioButtonExampleState();
    }
    
    class _RadioButtonExampleState extends State<RadioButtonExample> {
      // State variables for the selected values
      RadioGroup1 _selectedGroup1 = RadioGroup1.option1;
      RadioGroup2 _selectedGroup2 = RadioGroup2.option1;
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(title: Text('Radio Button Example')),
          body: Padding(
            padding: const EdgeInsets.all(16.0),
            child: Column(
              children: [
                Text('Group 1', style: TextStyle(fontSize: 20)),
                RadioListTile<RadioGroup1>(
                  title: Text('Option 1'),
                  value: RadioGroup1.option1,
                  groupValue: _selectedGroup1,
                  onChanged: (RadioGroup1? value) {
                    setState(() {
                      _selectedGroup1 = value!;
                    });
                  },
                ),
                RadioListTile<RadioGroup1>(
                  title: Text('Option 2'),
                  value: RadioGroup1.option2,
                  groupValue: _selectedGroup1,
                  onChanged: (RadioGroup1? value) {
                    setState(() {
                      _selectedGroup1 = value!;
                    });
                  },
                ),
                Divider(),
                Text('Group 2', style: TextStyle(fontSize: 20)),
                RadioListTile<RadioGroup2>(
                  title: Text('Option 1'),
                  value: RadioGroup2.option1,
                  groupValue: _selectedGroup2,
                  onChanged: (RadioGroup2? value) {
                    setState(() {
                      _selectedGroup2 = value!;
                    });
                  },
                ),
                RadioListTile<RadioGroup2>(
                  title: Text('Option 2'),
                  value: RadioGroup2.option2,
                  groupValue: _selectedGroup2,
                  onChanged: (RadioGroup2? value) {
                    setState(() {
                      _selectedGroup2 = value!;
                    });
                  },
                ),
              ],
            ),
          ),
        );
      }
    }
    

    Explanation: Enums for Radio Button Groups:

    Two enums, RadioGroup1 and RadioGroup2, are defined to represent the options for each group of radio buttons. State Variables:

    _selectedGroup1 and _selectedGroup2 are state variables that hold the currently selected values for each group. These variables are of the enum types defined above. RadioListTile Widgets:

    RadioListTile widgets are used to create the radio buttons. The value and groupValue properties use the enums, making the code more readable and manageable. When a radio button is selected, the onChanged callback updates the corresponding state variable. This approach ensures that you can easily manage multiple sets of radio buttons without hardcoding integer values, making the code more organized and easier to maintain.