I’m trying to change a variable on button click within another function. But i’m getting a syntax error under "currentPage" at this line:
"A" -> RegistrationScreen(currentPage)
The error says:
Type mismatch: inferred type is String but MutableState was expected
Here’s the code:
@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
Answers
When you use the
by
property delegate, the type ofcurrentPage
is notMutableState<String>
but justString
. The fact that it’s backed byMutableState
is hidden. You have two options:by
keyword and usecurrentPage
asMutableState
:by
delegate and add callback toRegistrationScreen
– this is preferred since havingState
as a function parameter is not recommended.The problem is in the
var currentPage by remember { mutableStateOf("A") }
statement.Here you are using
by
delegate, which is extracting the value and making thecurrentPage
asString
instead ofMutableState<String>
.By updating your code to
This way by avoiding the
by
delegate, you can capture theMutableState
object directly.Ref: https://kotlinlang.org/docs/delegated-properties.html