Having this sample, when checking the first item a...
# compose
l
Having this sample, when checking the first item and scrolling the list, the item is unchecked again, so the state is reset on scrolling, but why? I'm blind
Copy code
@Preview(device = Devices.PIXEL)
@Composable
private fun TestPreview() {
    LazyColumn {
        repeat(20) {
            item {
                val checkedState = remember { mutableStateOf(true) }
                Checkbox(
                    checked = checkedState.value,
                    onCheckedChange = { checkedState.value = it }
                )
                Spacer(modifier = Modifier.height(24.dp))
                Divider()
            }
        }
    }
}
f
Your example is somewhat contrived; you can't define the state inside the item lambda as the state will be discarded when the element exits the composition. You can achieve what you want like this, with the state outside
Copy code
@Preview(device = Devices.PIXEL)
@Composable
private fun TestPreview() {
    val size = 20
    val checkedState = remember { List(size) { true }.toMutableStateList() }
    LazyColumn {
        itemsIndexed(
            items = checkedState,
            key = { index, _ -> index }
        ) { index, checked ->
            Checkbox(
                checked = checked,
                onCheckedChange = { checkedState[index] = it }
            )
            Spacer(modifier = Modifier.height(24.dp))
            Divider()
        }
    }
}
z
If you want to keep the state inside the list item, I think you just need to use
rememberSaveable
l
Thanks @Francesc @Zach Klippenstein (he/him) [MOD] You saved my day! My actual code is somewhat more complex where I have to keep track of different states for one item (e.g. boolean for checkbox, float for slider, text for TextInput)
z
Francesc makes a good point though, it might make sense to hoist that state up in your view model layer or higher, instead of in the view layer.