Home > OS >  how can i change a RadioListTile button selection state after it has been initialized in flutter
how can i change a RadioListTile button selection state after it has been initialized in flutter

Time:04-30

I have created a RadioListTile based on a list of string items in an initStat function. But i could not get the radio button to change when it is being selected. If it were in a build function i could just call setState and it would have marked it as selected. How can i mark it as selected when i have created it at the beginning of the code. below here is the code i have tried, it actually print the selected radioTile value but i could not get it to change the selected state or the radio button selection.

List<String> list = ['Satisfied', 'Not Satisfied', 'Very Satisfied','Neutral'];

String _radioGroupValue = '';
int selectedRadioTile = 0;

void initState() {
super.initState();
selectedRadioTile = 0;
setState(() {
  for (int n = 0; n < list.length; n  ) {
    answersRadio.add(RadioListTile(
      value: n,
      groupValue: _radioGroupValue,
      onChanged: (val) {
        print('selected Radio index $val');
        setSelectedRadioTile(val);
        setState(() {

        });
      },
      title: Text(list[n]),
      selected: _radioGroupValue == list[n] ? true : false,
     ));
    }
  });
}

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

 child: Column(children: answersRadio,)

CodePudding user response:

class Example extends StatefulWidget {
  const Example({Key? key}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return _Examplestate();
  }
}

class _Examplestate extends State<Example> {
  List<String> list = [
    'Satisfied',
    'Not Satisfied',
    'Very Satisfied',
    'Neutral'
  ];

  String? _radioGroupValue;
  List<RadioListTile> answersRadio = [];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Stateful Widget'),
      ),
      body: Column(
        children: [
          for (var n in list)
            RadioListTile<String>(
              value: n,
              groupValue: _radioGroupValue,
              onChanged: (val) {
                _radioGroupValue = val;
                setState(() {});
              },
              title: Text(n),
              toggleable: true,
              selected: _radioGroupValue == n,
            )
        ],
      ),
    );
  }
}

CodePudding user response:

set int _groupValue = -1. define value for value : parameter according your need

Radio(
      materialTapTargetSize:
      MaterialTapTargetSize.shrinkWrap,
      visualDensity: VisualDensity.comfortable,
      activeColor: AppTheme.primaryColor,
      value: 1,
      groupValue: _groupValue,
      onChanged: (value) {
         setState(() {
            _groupValue = value as int;
         });
        },
      ),
  • Related