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

Iuhas Cezar

05/16/2022, 7:49 AM
Hi everyone, I have a weird issue with OutlinedTextField. I'm passing the initial value as a
Copy code
val textState = remember { mutableStateOf(costTextValue)}
but the value appears to be empty. If i print the value in log it shows correctly, but in my variable it's empty.
j

Ji Sungbin

05/16/2022, 7:57 AM
I think the use of State is wrong. Whenever recomposition,
textState
will be initialized with
costTextValue
being received as an argument to the function.
Wait a minute, I’m sorry I misunderstood.
As a tip, you can apply the delegate pattern to remember to omit direct calls to getters and setters.
c

Colton Idle

05/16/2022, 7:59 AM
Remove
val textState = remember { mutableStateOf(costTextValue)}
and just use costTextValue directly.
i

Iuhas Cezar

05/16/2022, 8:03 AM
I tried to use costTextValue directly but then the value in the textfield doesn't change when I write anything.
m

myanmarking

05/16/2022, 8:14 AM
try adding:
textState.value = costTextState
after textState declaration
i

Iuhas Cezar

05/16/2022, 8:18 AM
I did now, and it shows the correct value in the textfield but again it doesn't change the value in
onValueChanged
I'm guessing because of recomposition,
textState.value = costTextState
gets called again and resets it maybe.
o

Oleksandr Balan

05/16/2022, 8:53 AM
I would say, that
costTextValue
is dynamic and firstly
TextInputCost
is composed with
costTextValue = ""
. This leads to creating an inner state
textState
with this value. Then
TextInputCost
is recomposed again with non-empty
costTextValue
, but inner state is not updated with a new value because
remember
has no keys. Try to add a key to remember, so that inner state is recreated correctly:
Copy code
val textState = remember(costTextValue) { mutableStateOf(costTextValue) }
c

Chris Fillmore

05/16/2022, 9:24 AM
and it shows the correct value in the textfield but again it doesn’t change the value in
onValueChanged
What makes you say this? The value of the text field reflects updates to
textState
. So if your text field is updating, then your
onValueChange
is working correctly.
Can I also suggest the following: rename
costTextValue
to
initialCostTextValue
, because that is all it is, the initial value for
textState
i

Iuhas Cezar

05/16/2022, 9:55 AM
@Chris Fillmore I meant that my text field isn't updating in onValueChanged.
But I think I found a solution, maybe not the best one, I'm gonna update the
costTextValue
directly in the viewModel from
onValueChange
v

Vsevolod Kaganovych

05/16/2022, 12:53 PM
I have kind of a workaround. I didn't find anything better, decided to come back later to this.
Copy code
var text by remember { mutableStateOf("") }
        LaunchedEffect(*your initial word*) {
            text = *your initial word*
        }
🙌 1
i

Iuhas Cezar

05/16/2022, 1:11 PM
Thanks for your answers guys.
8 Views