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?
While Johann's solution works for OP's specific scenario, to be able to assign the passed parameter another value, you'd need a Lambda function for each change, like this:
@Composable
fun AnotherFunc(mutableValue: Boolean, onMutableValueChange: (Boolean) -> Unit){
onMutableValueChange(false) // myMutableState would now also be false
}
@Composable
fun Func() {
val myMutableState by remember { mutableStateOf(true) }
Column {
AnotherFunc(mutableValue = myMutableState, onMutableValueChange = {myMutableState = it})
}
}
(Boolean) -> Unit means a function that accepts a Boolean as a parameter and doesn't have a return value. Simply pass a lambda function to change mutableValue as seen in the example above, and call it in AnotherFunc whenever you need to change mutableValue.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With