Jetpack Compose forgets a remembered value when switching tabs

77 Views Asked by At

I'm trying to learn Jetpack Compose multiplatform in Kotlin. Below is a minimal, compilable example:

@Composable
fun TestScreen(){
    var checked by remember { mutableStateOf(true) }
    Checkbox(checked, {checked = !checked})
}

@Composable
fun TabContainer() {
    var index by mutableStateOf(0)
    val tabs = listOf("Tab A", "Tab B")
    MaterialTheme {
        Column(Modifier.fillMaxWidth()) {
            TabRow(index) {
                tabs.forEachIndexed { i, title ->
                    Tab(index == i, { index = i }, text = { Text(title) })
                }
            }
            when (index) { 0 -> TestScreen() }
        }
    }
}

fun main() = application { TabContainer() }

As you can see, the checkbox in TestScreen is checked by default. I want it to remain unchecked when I come back to it after switching a tab. However, it reverts to being checked when I switch to Tab B and back. Is the only way to solve this a global variable?

1

There are 1 best solutions below

2
Name On

Did you try checked state move to upper compose?

@Composable
fun TestScreen(
    checked: Boolean,
    onCheckedChange: (Boolean) -> Unit
) {
    Checkbox(
        checked = checked,
        onCheckedChange = {
            onCheckedChange(it)
        }
    )
}

@Composable
fun TabContainer() {
    var index by remember { mutableIntStateOf(0) }
    val tabs = listOf("Tab A", "Tab B")

    var checked by remember { mutableStateOf(true) }

    MaterialTheme {
        Column(Modifier.fillMaxWidth()) {
            TabRow(index) {
                tabs.forEachIndexed { i, title ->
                    Tab(index == i, { index = i }, text = { Text(title) })
                }
            }
            when (index) {
                0 -> TestScreen(
                    checked = checked,
                    onCheckedChange = {
                        checked = !checked
                    }
                )
            }
        }
    }
}