About Radio Button in ListView.builder() flutter

时间秒杀一切 提交于 2021-01-28 13:49:20

问题


I am working on Radio Button in a ListView.builder() but when I select any of the radio button it is selecting each and every radio button rather than selected one.

My code is given below:

ListView.builder(
                    itemCount: 67,
                    itemBuilder: (BuildContext context, int index) {
                      return _buildCheckListItems(index);
                    }),


Widget _buildCheckListItems(int index) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: <Widget>[
        Text(
          'Seat Belts',
          style: TextStyle(fontSize: 17),
        ),
        Container(
          width: 200,
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: <Widget>[
              Radio(
                value: 1,
                groupValue: selectedRadio,
                activeColor: Colors.green,
                onChanged: (val) {
                  changeValue(val);
                },
              ),
              Radio(
                value: 2,
                groupValue: selectedRadio,
                activeColor: Colors.green,
                onChanged: (val) {
                  changeValue(val);
                },
              )
            ],
          ),
        ),
      ],
    );
  }


changeValue(int val) {
    setState(() {
      selectedRadio = val;
    });
  }

The output result of above code is as follow:

Output result


回答1:


The key point here is that you are using a same groupValue: selectedRadio, Each radio button group must have different groupValue otherwise it will shared the same change.

If you do not want to specify name for each radio button group you can just create a new .dart file:

import 'package:flutter/material.dart';

class buildCheckListItems extends StatefulWidget {
  final int index;
  buildCheckListItems(this.index); //I don't know what is this index for but I will put it in anyway
  @override
  _buildCheckListItemsState createState() => _buildCheckListItemsState();
}

class _buildCheckListItemsState extends State<buildCheckListItems> {
  int selectedRadio = -1;

  changeValue(int val) {
    setState(() {
      selectedRadio = val;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: <Widget>[
        ...
      ],
    );
  }
}

and now everything should be working just fine.



来源:https://stackoverflow.com/questions/62330919/about-radio-button-in-listview-builder-flutter

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!