TextField with Kotlin StateFlow

Issue

I’d like to have a TextField bound to a MutableStateFlow that comes from a view model. This is how I set it up:

@Composable
fun MyTextField(textFlow: MutableStateFlow<String>) {
    val state  textFlow.collectAsState(initial  "")
    TextField(
        value  TextFieldValue(state.value),
        onValueChange  { textFlow.value  it.text },
        label  { Text(text  "Label") }
    )
}

When I type something into the text field, it behaves really strangely. For example, if I type ‘asd’, it ends up with ‘asdasa’. How can I update textFlow.value without messing up with the text field?

Solution

This error is caused by the usage of TextFieldValue with Flow.

To fix this, set the value of the TextField to just state.value and then on text change set the value with textFlow.value it.

@Composable
fun MyTextField(textFlow: MutableStateFlow<String>) {
    val state  textFlow.collectAsState(initial  "")
    TextField(
        value  state.value,
        onValueChange  { textFlow.value  it },
        label  { Text(text  "Label") }
    )
}

Answered By – Stefano Sansone

Leave a Comment