https://kotlinlang.org logo
#compose
Title
# compose
d

dimsuz

09/01/2020, 5:56 PM
Why is this not working? No text appears in the input field
Copy code
val inputState: TextFieldValue by mutableStateOf(TextFieldValue())
TextField(value = inputState.value, onValueChange = { inputState = it })
But if I wrap in
remember
than text input starts working. I am asking because Compose State codelab has examples which have only
by mutableStateOf
and no
remember
(for example in ViewModel section), but TextField turns out to be special here?
f

flosch

09/01/2020, 6:04 PM
I think I already wrote you this before, but the codelab should provide all the info you need.
remember
is needed if you want to keep the
MutableState
across recompositions of your `Composable`s. In the
ViewModel
you do not need it, because the
ViewModel
is not recomposed and the
MutableState
is not lost.
z

Zach Klippenstein (he/him) [MOD]

09/01/2020, 6:05 PM
Irs not TextField that's special, it's because you're in a composable function. Composable functions get re-invoked (recomposed) whenever anything changes. So in your case, whenever you type a key, it re-invokes your function, which recreates your mutable state with an empty string, and passes that to the TextField composable. You need remember, as florian said, so that the same instance of the state is preserved across compositions.
👍 1
d

dimsuz

09/01/2020, 6:05 PM
Florian, thanks. This was the last bit I asked, without a reply, I thought you didn't see it and decided to post here for visibility.
👍 1
Now I get this: in VM case it stores state, otherwise it is stored in a "compose tree" and I need to ensure it is remembered
2 Views