如何将委托的 mutableVariable 传递给 Compose 函数?

Ely*_*lye 6 android kotlin android-jetpack-compose

我试图将 MutableState 变量传递给另一个函数。下面这一切都很好。但我不喜欢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>) {
}
Run Code Online (Sandbox Code Playgroud)

所以我决定使用val myMutableState by remember { mutableStateOf(true) },如下所示。我不再需要使用myMutableState.value如下所示。

不幸的是,下面的内容无法编译。这是因为我无法将它传递给函数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>) {
}
Run Code Online (Sandbox Code Playgroud)

我如何仍然使用by并仍然能够通过函数传递 MutableState?

And*_*Dev 4

=-0987我们的可组合函数应该只接受一个布尔值:

@Composable
fun AnotherFunc(mutableValue: Boolean) {
}
Run Code Online (Sandbox Code Playgroud)

不确定为什么您的可组合函数(AnotherFun)需要具有可变状态。当值改变时,调用函数(Fun)会自动重组,触发AnotherFun的重组。

  • 如果我想给它分配一个新值怎么办?因为它应该是可变的 (10认同)