Home > OS >  Switch control in function not working after being hoisted
Switch control in function not working after being hoisted

Time:06-22

After hoisting my isChecked variable, it seems that the Switch is not working whenever I click on it.

@Composable
fun PreferencesScreen(navController: NavController) {
    var isChecked by rememberSaveable { mutableStateOf(false) }

    Scaffold(
        topBar = {...},
        content = { LazyColumn(modifier = Modifier.padding(it).fillMaxSize()) {
                item {
                    MyPreference(isChecked, "Test preference")
                }
            }
        },
        containerColor = MaterialTheme.colorScheme.background
    )
}

@Composable
fun MyPreference(isChecked: Boolean, title: String) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .toggleable(value = isChecked, onValueChange = { isChecked }),
    ) {
        Text(text = title)
        Switch(checked = isChecked, onCheckedChange = null)
    }
}

CodePudding user response:

The general pattern for state hoisting in Jetpack Compose is to replace the state variable with two parameters:

value: T: the current value to display

onValueChange: (T) -> Unit: an event that requests the value to change, where T is the proposed new value

So:

@Composable
fun MyPreference(isChecked: Boolean, title: String, onCheckedChange: (Boolean) -> Unit) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .toggleable(value = isChecked, onValueChange = onCheckedChange),
    ) {
        Text(text = title)
        Switch(checked = isChecked, onCheckedChange = null)
    }
}

And:

//...
item {
    MyPreference(isChecked, "Test preference", {isChecked = !isChecked})
}
//...
  • Related