Search code examples
flutterflutter-layoutflutter-dependenciesflutter-test

Make RadiobButton Dynamically in Listview Builder in but select one button at a time in flutter


I used this code but select all buttons like a checkbox

ListView.builder(
                              shrinkWrap: true,
                              physics: ClampingScrollPhysics(),
                              itemCount: sampleData.length,
                              itemBuilder: (context, index) => ButtonBar(
                                alignment: MainAxisAlignment.center,
                                children: <Widget>[
                                  Radio(
                                    groupValue: groupValue[index],
                                    value: value[index][0],
                                    onChanged: (newValue) => setState(() => groupValue[index] = newValue as int),
                                  ),
                                  
                                ],
                              ),
                            ),

Please correct me where I am wrong

enter image description here

I want to create like this with dynamically and one selection at a time.


Solution

  • First create a Model class like tis;

    class ItemModel {
      final String title;
      final int value;
      ItemModel({required this.title, required this.value});
    }
    

    then create a list like this:

    List<ItemModel> _testList = [
        ItemModel(title: 'test1', value: 0),
        ItemModel(title: 'test2', value: 1),
        ItemModel(title: 'test3', value: 2),
      ];
    
      var groupValue = -1;
    

    then use this:

    ListView.builder(
              physics: ClampingScrollPhysics(),
              itemCount: _testList.length,
              itemBuilder: (context, index) => Padding(
                padding: const EdgeInsets.symmetric(horizontal: 8.0),
                child: ButtonBar(
                  alignment: MainAxisAlignment.spaceBetween,
                  buttonPadding: EdgeInsets.zero,
                  children: <Widget>[
                    Text(_testList[index].title),
                    Radio(
                      groupValue: groupValue,
                      value: _testList[index].value,
                      onChanged: (newValue) =>
                          setState(() => groupValue = newValue as int),
                    ),
                  ],
                ),
              ),
            )
    

    enter image description here