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

Jetpack Compose val cannot be reassigned

I want to pass state but it throws error "val cannot be reassigned".

@Composable
fun MyUi() {
    var showContent by remember { mutableStateOf(false) }
    if (showContent) {
        MyButton(showContent)  
    }
}

@Composable
fun MyButton(showContent: Boolean) {
    // very long content
    Button(onClick = {
        showContent = true
    }) {
        Text(text = "Very long content")
    }
}

>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 should make your composables statelesss and pass events up, change it like this, where the top composable is responsible for mutating the flag

@Composable
fun MyUi() {
    var showContent by remember { mutableStateOf(false) }
    if (showContent) {
        MyButton(
            onClick = {
                showContent = true
            }
        )
    }
}

@Composable
fun MyButton(onClick: () -> Unit) {
    // very long content
    Button(onClick = onClick) {
        Text(text = "Very long content")
    }
}
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