- I have a LazyColumn in which
items()exist that holds 5 checkboxes, and the state of these can be controlled by a single parent variable as well as with a specific variable. The code is below:
val areAllChecked = rememberSaveable {
mutableStateOf(false)
}
MyApplicationTheme {
LazyColumn(modifier = Modifier.fillMaxSize()) {
item {
IconButton(onClick = { areAllChecked.value = false }) {
Icon(imageVector = Icons.Default.Clear, contentDescription = null)
}
}
item {
Row(verticalAlignment = Alignment.CenterVertically){
Text(text = "Parent")
Checkbox(checked = areAllChecked.value, onCheckedChange = {
areAllChecked.value = it
})
}
}
items(5) {
val isChecked = rememberSaveable(areAllChecked.value) {
mutableStateOf(areAllChecked.value)
}
Row(verticalAlignment = Alignment.CenterVertically){
Text(text = it.toString())
Checkbox(checked = isChecked.value, onCheckedChange = {
isChecked.value = it
})
}
}
}
}
Here,
areAllCheckedis a parent variable for controlling the state, andisCheckedis a local variable for checkboxes that changes whenareAllCheckedgets changed as expected.But when I press the icon button, all of the checkboxes' states will be false only if
areAllCheckedis true. If it's not true, the local variable, which isisChecked, remain unchanged when they should also be set to false, as the IconButton onClick triggers theareAllCheckedto false.I've added the GIF here to show what I'm trying to solve.
How can i fix this?
Thank you.
You need to wrap your item into the
DataClass to manage the state of each item easily.Here is the full example
Why use
LaunchedEffectbecause we don't want to load it every time. We want to change only when theCheckBoxof Parent changes.Whenever changes are made in the single item we loop through and change its value and assign a new list to current.