选中时更改单选按钮的值

Change the value of the radio button when selected

我有一个字符串列表

List<String> answerOptions=['Apple','Orange','Grapes','Kiwi'];

并且我创建了一个名为 QuizRa​​dioButton 的自定义单选按钮文件

class QuizRadioButton extends StatefulWidget {
  final String label;
  final void Function(dynamic) onChanged;

 const QuizRadioButton(
     {required this.label, required this.onChanged, Key? key})
      : super(key: key);

    @override
     _QuizRadioButtonState createState() => _QuizRadioButtonState();
    }

    class _QuizRadioButtonState extends State<QuizRadioButton> {
     int? _value = 0;

      @override
       Widget build(BuildContext context) {
        return Padding(
        padding: const EdgeInsets.all(16.0),
        child: Row(
         children: [
           Radio<int>(
            value: 1,
            groupValue: _value,
            onChanged: (value) => setState(() => _value = value),
            ),
            Text(widget.label, style: Theme.of(context).textTheme.headline3),
    ],
  ),
);
}
}

我使用了这个单选按钮 class 并且我使用上面提到的列表填充了 4 个单选按钮

Widget content(BuildContext context){
return Padding(
  padding: const EdgeInsets.all(16.0),
  child: Column(
    children: <Widget>[
      Text('which fruit of these are red in color ?'),
      SizedBox(height: 30.0,),
      for(int i=0;i<answerOptions.length;i++)Container(
        child:QuizRadioButton(label: answerOptions[i], onChanged: (value){}) ,
      )


    ],
  ),
);
}

我得到的输出是

现在我们可以select一次全部4个单选按钮,我想要的是如果我想选择苹果,标签为苹果的单选按钮应该是true,其他的是false。请帮助

int groupVal=0;

实施:

Widget content(BuildContext context){
  return Padding(
    padding: const EdgeInsets.all(16.0),
    child: Column(
      children: <Widget>[
        Text('which fruit of these are red in color ?'),
        SizedBox(height: 30.0,),
        for(int i=0;i<answerOptions.length;i++)
          Container(
            child:QuizRadioButton(label: answerOptions[i], onChanged: (value){
              setState(() {
                groupVal=value;
              });
            }, index: i, groupVal: groupVal) ,
          )

      ],
    ),
  ),
}

您的 QuizRa​​dioButton:

class QuizRadioButton extends StatefulWidget {
  final String label;
  final void Function(dynamic) onChanged;
  int index,groupVal;

  QuizRadioButton(
      {required this.label, required this.groupVal, required this.onChanged, required this.index, Key? key})
      : super(key: key);

  @override
  _QuizRadioButtonState createState() => _QuizRadioButtonState();
}

class _QuizRadioButtonState extends State<QuizRadioButton> {

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(16.0),
      child: Row(
        children: [
          Radio<int>(
            value: widget.index,
            groupValue: widget.groupVal,
            onChanged: widget.onChanged,
          ),
          Text(widget.label, style: Theme.of(context).textTheme.headline3),
        ],
      ),
    );
  }
}