For readability purposes, I want to extract the NavigationBar composable in another function. Same with PreviousButton. Therefore I want to pass the mutableState of index to a these functions. But passing index as a parameter does not work, because I cannot update the state. What can I do?
@Composable
fun MyChickensScreen(){
val art: List<Art> = Datasource().loadArt()
var index: Int by remember { mutableStateOf(0) }
// IDE suggests making index a val,
// but I want to update the state in another composable.
//...
NavigationBar(index = index)
}
}
//NavigationBar passes index to the PreviousButton Composable
@Composable
private fun PreviousButton(index: Int) {
Button(
onClick = { index = handlePrevClick(index) }, //Error: Val cannot be reassigned for index
) {
//...
}
}
>Solution :
You can add a lambda function for updating to value on the mutable state to NavigationBar and PreviousButton:
@Composable
fun MyChickensScreen(){
val art: List<Art> = Datasource().loadArt()
var index: Int by remember { mutableStateOf(0) }
// IDE suggests making index a val,
// but I want to update the state in another composable.
//...
NavigationBar(
index = index,
updateIndex = { index = it }
)
}
@Composable
private fun PreviousButton(
index: Int,
updateIndex: (index: Int) -> Unit
) {
Button(
onClick = { updateIndex(handlePrevClick(index)) },
) {
//...
}
}
Now you can update index mutable state by passing new value to updateIndex lambda function.