Home > database >  Kotlin: How to set the mutableState of an Integer in another composable function?
Kotlin: How to set the mutableState of an Integer in another composable function?

Time:12-03

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
    ) {
        //...
    }
}

CodePudding user response:

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.

CodePudding user response:

There is a probably better solution, but what I have been doing are:

Put a variable inside viewmodel, and make an update method, pass the view model or method to composable

Or

Pass method down to update the index

NavigationBar(index = index, 
 update ={it->
     index = it
})
}

@Composable
private fun PreviousButton(index: Int, update: (Int)-> Unit {
    Button(
        onClick = { update.invoke(index) },
    ) {
        //...
    }
}
  • Related