android-jetpack-composeandroid-compose-textfield

How is TextField 's "onValueChange" parameter updated in Jetpack Compose


Having this simple example:

@Composable
fun SimpleFilledTextFieldSample() {
    var text by remember { mutableStateOf("Hello") }

    TextField(
        value = text,
        onValueChange = { text = it },
        label = { Text("Label") }
    )
}

I'm trying to understand if every time a user presses a key "onValueChange" is updated (meaning called)?
I'm having trouble finding the answer in the android jetpack compose documentations..


Solution

  • Your understanding is correct. Whenever the text in the TextField is modified, onValueChange will be called with the whole current text.

    When you type "ABC" into the empty TextField, the onValueChange callback will return

    A
    AB
    ABC
    

    The TextField documentation says

    onValueChange: (String) -> Unit
    the callback that is triggered when the input service updates the text. An updated text comes as a parameter of the callback

    They are using the rather generic "Input Service" term here as there a various ways to generate text into a TextField, also known as IME:

    Whenever an IME generates or changes the text in the TextField, onValueChange is triggered. It is then your job to update the value variable with the fresh text to correctly update the UI.