Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading