Android Studio 无法在另一个函数中更改jetpack compose变量

ggazkfy8  于 11个月前  发布在  Android
关注(0)|答案(2)|浏览(135)

我试图在另一个函数中更改按钮单击时的变量。但我在“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")
    }
}

cx6n0qe3

cx6n0qe31#

当你使用byproperty delegate时,currentPage的类型不是MutableState<String>,而是String。它被MutableState支持的事实被隐藏了。你有两个选择:
1.删除by关键字并将currentPage用作MutableState

val currentPage = remember { mutableStateOf("A") }
CrossSlide(targetState = currentPage.value) { screen ->
    when (screen) {
        "A" -> RegistrationScreen(currentPage)
        "B" -> LoginScreen()
    }
}

字符串
1.保留by委托并向RegistrationScreen添加回调-这是首选,因为不建议将State作为函数参数。

@Composable
fun CrossSlideExample() {
    var currentPage by remember { mutableStateOf("A") }

    CrossSlide(targetState = currentPage) { screen ->
        when (screen) {
            "A" -> {
                RegistrationScreen(
                    currentPage = currentPage,
                    onCurrentPageChange = { currentPage = it },
                )
            }
            "B" -> LoginScreen()
        }
    }
}

@Composable
fun RegistrationScreen(
    currentPage: String, // you don't use the value itself here, so not needed
    onCurrentPageChange: (String) -> Unit,
){
    Button(onClick = {
        onCurrentPageChange("B")
    }) {
        Text(text = "GO TO LOGIN")
    }
}

new9mtju

new9mtju2#

问题出在var currentPage by remember { mutableStateOf("A") }语句中。
这里使用的是by委托,它提取值并将currentPage转换为String而不是MutableState<String>
通过更新代码,

val currentPage = remember { mutableStateOf("A") }

        CrossSlide(targetState = currentPage.value) { screen ->
            when (screen) {
                "A" -> RegistrationScreen(currentPage)
                "B" -> LoginScreen()
            }
        }

字符串
这样,通过避免by委托,您可以直接捕获MutableState对象。
参考:https://kotlinlang.org/docs/delegated-properties.html

相关问题