Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TextField with Kotlin StateFlow

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?

like image 566
Milack27 Avatar asked Sep 17 '25 18:09

Milack27


1 Answers

You should not use MutableStateFlow as the backing for a TextField (as of Compose 1.5 and earlier). You should prefer MutableState instead. See this article for an in depth explanation of why.

like image 126
Sean Avatar answered Sep 19 '25 09:09

Sean