I have a ListViewBuilder with data from Firestore. In my list I want return a ListTile and add CheckBox to the ListTile or return a CheckBoxListTile whichever works better.
But for some reasons, which I can tell, I can’t select the checkbox in both cases.
When I return a ListTile with the checkbox with single checkbox value, it checks all the boxes when I select only one. When I try set it to multiple check with checkList = []
, nothing selects at all
When I return a CheckBoxListTile, I am not able to select anything either. Can someone help me with this, please. I’ve been stuck for ages.
This is my code for returning CheckBoxListTile
List<int> selectedList = [];
List<bool> isCheckedList = [];
StreamBuilder(
stream: FirebaseFirestore....
builder: (context, snapshot) {
if (snapshot.hasData) {
return ListView.builder(
itemCount: snapshot.data!.docs.length,
itemBuilder: (context, index) {
final info = snapshot.data!.docs[index];
isCheckedList =
List.filled(snapshot.data!.docs.length, false);
var timestamp = info.get("Time") as Timestamp;
final isRead = info.get("Read");
return CheckboxListTile(
controlAffinity: ListTileControlAffinity.leading,
activeColor: Colors.green,
checkColor: Colors.green,
tileColor: isRead == "No" ? Colors.teal.shade100 : null,
title: TextScroll(
"${info.get("title")}. ",
velocity: const Velocity(pixelsPerSecond: Offset(30, 0)),
style: const TextStyle(fontWeight: FontWeight.bold),
),
value: isCheckedList[index],
onChanged: (value) {
setState(() {
isCheckedList[index] = value!;
if (value) {
selectedList.add(index);
} else {
selectedList.remove(index);
}
});
},
);
},
);
}
return Center(
child: Text("Whatever"),
);
},
),
3
Answers
Move the
isChecked
List declaration outside the ListView builder. Right now, it’s causing all checkboxes to reset when one is checked due to its placement within the ListView.selectedList
andisCheckedList
are moved to the state of the Build widget. This way, the state is maintained even when the build method is called again. Make sure to replace FirebaseFirestore…. with your actual stream. This should fix the issue you’re experiencing with selecting checkboxes in your list.