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
i want to create like this with dynamically and one selection at a time.
CodePudding user response:
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) => ButtonBar(
alignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Text(_testList[index].title),
Radio(
groupValue: groupValue,
value: _testList[index].value,
onChanged: (newValue) =>
setState(() => groupValue = newValue as int),
),
],
),
)
CodePudding user response:
first of all, You have used a stateful widget for each button. after that, you have defined a boolean variable in that class. finally, you have called a setState when u press on it. something like this:
ListView.builder(
physics: ClampingScrollPhysics(),
itemCount: _testList.length,
itemBuilder: (context, index) => Test()
);
second class:
class Test extends StatefulWidget {
const Test({Key? key}) : super(key: key);
@override
State<Test> createState() => _TestState();
}
class _TestState extends State<Test> {
bool active = false;
@override
Widget build(BuildContext context) {
return Row(
children: [
Checkbox(
value: active,
onChanged: (v) {
setState(() {
active = v!;
});
}),
Text("text")
],
);
}
}