Home > database >  Type mismatch when creating state for Switch
Type mismatch when creating state for Switch

Time:07-03

Even when I change the parameter isChecked type to MutableState<Boolean> another error is still returned.

Type mismatch. Required: MutableState. Found: Boolean.

@Composable
fun PreferencesScreen(navController: NavController) {
    var isChecked = remember { mutableStateOf(false) }

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

@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)
    }
}

CodePudding user response:

TLDR: Declare the variable isChecked with by:

var isChecked by remember { mutableStateOf(false) }

The function mutableStateOf returns a State<T>, where T is Boolean in this case. So, when you read or write to isChecked, you're dealing with a State variable, not the Boolean you expect.

When you use by (and import the appropriate methods), you create a variable which has custom getters and setters; in this case, when you read the variable, it actually reads the state value, and when you write to the variable, it actually writes to the state. It's just a syntax sugar, in the end. This Kotlin feature is called Delegate. You can read more in their documentation if you want to learn more about it.

  • Related