问题
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