Home > Net >  Getting text value from active radio button in Flutter
Getting text value from active radio button in Flutter

Time:02-19

Hi my goal is to have a list of RadioButtons where each of them will have their unique name. At the top there is a Text() field which will take that name from radio button and update it accordingly to Radio buttons name.

Here is an example:

enter image description here

And when you press Option 2 radio button the Text field changes according to it:

enter image description here

How can I achieve this because Im fairly new to Flutter and Dart. Thanks in advance

CodePudding user response:

the code:

class HomePage  extends StatefulWidget {

    const HomePage ({Key? key, required this.title}) : super(key: key);
    final String title;

    @override
    State<HomePage > createState() => _HomePage ();
  }

  class _HomePage  extends State<HomePage > {

    String _groupValue = '';

    void checkRadio(String value ) {
      setState(() {
        _groupValue = value;
      });
    }

    @override
    Widget build(BuildContext context) {

     return Scaffold(
        appBar: AppBar(

        ),
        body: SafeArea(
          child: Center(
            child: Column(
              children: [
                Container(height: 50,),
                Text(_groupValue),
                ListTile(
                  title: Text('Option1'),
                  leading: Radio(
                    value: 'Option1',
                    groupValue: _groupValue,
                    onChanged: (value) {
                         checkRadio(value as String);
    }
                  ),
                ),
                ListTile(
                  title: Text('Option2'),
                  leading: Radio(
                      value: 'Option2',
                      groupValue: _groupValue,
                      onChanged: (value) {
                        checkRadio(value as String);
                }
            ),
          ),
          ListTile(
            title: Text('Option3'),
            leading: Radio(
                value: 'Option3',
                groupValue: _groupValue,
                onChanged: (value) {
                  checkRadio(value as String);
                }
            ),
          ),
          ListTile(
            title: Text('Option4'),
            leading: Radio(
                value: 'Option4',
                groupValue: _groupValue,
                onChanged: (value) {
                  checkRadio(value as String);
                }
            ),
          ),
          ListTile(
            title: Text('Option5'),
            leading: Radio(
                value: 'Option5',
                groupValue: _groupValue,
                onChanged: (value) {
                  checkRadio(value as String);
                }
            ),
          ),

        ],
      ),

    )
  ),
);
  }

  }

The result:

enter image description here

  • Related