我试图在另一个函数中更改按钮单击时的变量。但我在“currentPage”下面的这一行得到一个语法错误:
"A" -> RegistrationScreen(currentPage)
字符串
错误表示:
- 类型不匹配:推断的类型为String,但应为MutableState *
下面是代码:
@Composable
fun CrossSlideExample() {
var currentPage by remember { mutableStateOf("A") }
CrossSlide(targetState = currentPage) { screen ->
when (screen) {
"A" -> RegistrationScreen(currentPage)
"B" -> LoginScreen()
}
}
}
@Composable
fun RegistrationScreen(currentPage:MutableState<String>){
Button(onClick = {
currentPage.value = "B"
}) {
Text(text = "GO TO LOGIN")
}
}
@Composable
fun LoginScreen(){
Button(onClick = { /*TODO*/ }) {
Text(text = "GO BACK TO REGISTRATION")
}
}
型
2条答案
按热度按时间cx6n0qe31#
当你使用
by
property delegate时,currentPage
的类型不是MutableState<String>
,而是String
。它被MutableState
支持的事实被隐藏了。你有两个选择:1.删除
by
关键字并将currentPage
用作MutableState
:字符串
1.保留
by
委托并向RegistrationScreen
添加回调-这是首选,因为不建议将State
作为函数参数。型
new9mtju2#
问题出在
var currentPage by remember { mutableStateOf("A") }
语句中。这里使用的是
by
委托,它提取值并将currentPage
转换为String
而不是MutableState<String>
。通过更新代码,
字符串
这样,通过避免
by
委托,您可以直接捕获MutableState
对象。参考:https://kotlinlang.org/docs/delegated-properties.html