Home > Enterprise >  How can I pass a delegated mutableVariable to a Compose function?
How can I pass a delegated mutableVariable to a Compose function?

Time:01-15

I'm trying to pass the MutableState variable over another function. The below is all good. But I don't like the myMutableState.value

@Composable
fun Func() {
    val myMutableState = remember { mutableStateOf(true) }
    Column {
        AnotherFunc(mutableValue = myMutableState)
        Text(if (myMutableState.value) "Stop" else "Start")
    }
}

@Composable
fun AnotherFunc(mutableValue: MutableState<Boolean>) {
}

So I decided to use val myMutableState by remember { mutableStateOf(true) }, as shown below. I no longer need to use myMutableState.value as shown below.

Unfortunately, the below won't compile. This is because I cannot pass it over the function AnotherFunc(mutableValue = myMutableState)

@Composable
fun Func() {
    val myMutableState by remember { mutableStateOf(true) }
    Column {
        AnotherFunc(mutableValue = myMutableState) // Error here
        Text(if (myMutableState) "Stop" else "Start")
    }
}

@Composable
fun AnotherFunc(mutableValue: MutableState<Boolean>) {
}

How can I still use by and still able to pass the MutableState over the function?

CodePudding user response:

Your composable function should just take a boolean:

@Composable
fun AnotherFunc(mutableValue: Boolean) {
}

Not sure why your composable function (AnotherFun) needs to have a mutable state. The calling function (Fun) will automatically recompose when the value changes, triggering recomposition of AnotherFun.

  •  Tags:  
  • Related