I'd like to know how I can change variables INSIDE a Composable via a method. Of course i can do something like:
var test: String by remember { mutableStateOf("hello") }
and can change it like I want to, like (although it is a stupid example)
[stuff...].pointerInput(Unit) {
detectDragGestures(...)
{ change, dragAmount ->
test=dragamount.toString()
}
}
but how would i change the variable with some complicated method eg
[stuff...].pointerInput(Unit) {
detectDragGestures(...)
{ change, dragAmount ->
changeText(dragAmount)
}
}
I can only use methods outside of the composable to assign it to the value, aka
test=getMyNewTest(dragAmount)
But how can i change my 'fields' inside a composable, so that i can modify 'test' directly in my method?
If the method can see the a mutable variable (ie share a lexical scope) it can change it. For changeText
to be able to change test
, it must either have test
in scope or receive a mutable reference to test
as a parameter. Compose doesn't change this.
Any answer to this question outside of compose (eg class scopes, modules scopes, global scopes, closure capture, reference passing, etc.) works in compose as well.
For example, you could define the function as local to the composable function as,
@Composable
fun Example() {
var test by remember { mutableStateOf("hello") }
fun changeText(amount: Float) {
test = amount.toString()
}
...
[stuff...].pointerInput(Unit) {
detectDragGestures(...)
{ change, dragAmount ->
changeText(dragAmount)
}
}
...
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.