I want to create checkbox where users can choose only one item from list clicking by checkbox. I understand that I should use index for achieve my goal, because now I can check all items, not one by one. Also I created hardcoded data which look like the actual data from API.
class CkeckList extends StatefulWidget {
const CkeckList({Key? key}) : super(key: key);
@override
State<CkeckList> createState() => _CkeckListState();
}
class _CkeckListState extends State<CkeckList> {
List checkListItems = [
{
"id": 0,
"title": "Sunday",
},
{
"id": 1,
"title": "Monday",
},
];
int? isChecked;
bool isSelected = false;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: ListView.builder(
itemCount: checkListItems.length,
itemBuilder: (context, index) {
return CheckboxListTile(
title: Text(checkListItems[index]['title']),
value: isSelected,
onChanged: (value) {
checkListItems[index]['id'] = value;
});
}),
);
}
}
CodePudding user response:
class CkeckList extends StatefulWidget {
const CkeckList({Key? key}) : super(key: key);
@override
State<CkeckList> createState() => _CkeckListState();
}
class _CkeckListState extends State<CkeckList> {
List checkListItems = [
{
"id": 0,
"title": "Sunday",
},
{
"id": 1,
"title": "Monday",
},
];
// if you want to set default selected item you can assign its index here
int? selectedItemIndex;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: ListView.builder(
itemCount: checkListItems.length,
itemBuilder: (context, index) {
return CheckboxListTile(
title: Text(checkListItems[index]['title']),
value: (selectedItemIndex==null)?false:(selectedItemIndex == index),
onChanged: (value) {
checkListItems[index]['id'] = value;
selectedItemIndex = index;
});
}),
);
}
}
CodePudding user response:
Try this.
class CkeckList extends StatefulWidget {
const CkeckList({Key? key}) : super(key: key);
@override
State<CkeckList> createState() => _CkeckListState();
}
class _CkeckListState extends State<CkeckList> {
List checkListItems = [
{
"id": 0,
"title": "Sunday",
},
{
"id": 1,
"title": "Monday",
},
];
int? isChecked;
List<bool> checkedList = [];
@override
Widget build(BuildContext context) {
checkedList.clear();
checkListItems.forEach((element) {
checkedList.add(element['id']==0?false:true);
});
return Scaffold(
appBar: AppBar(),
body: ListView.builder(
itemCount: checkListItems.length,
itemBuilder: (context, index) {
return CheckboxListTile(
title: Text(checkListItems[index]['title']),
value: checkedList[index],
onChanged: (value) {
checkListItems[index]['id'] = value;
});
}),
);
}
}