Skip to the workspace
Pebellslearn by building
Building Screens with Jetpack Compose  ›  Lesson

TextField and remember

TextField 15 minA TextField shows the value you give it and reports edits through onValueChange, so its text must be held in state that you update.

android / TextField and remember

Explore each scene at your own pace.

01 · The rule

The rule

TextField and remember

Sprout's add-plant screen has a name field. A first attempt often looks like this, and typing into it does absolutely nothing:

TextField(value = "", onValueChange = { })

Nothing is broken. The field is doing exactly what it was told. Understanding why is the key to all Compose input.

The rule

The field shows your state and reports edits; you write them back.

A TextField does not own its text. It has two halves:

  • value — what to display. It always shows exactly this.
  • onValueChange — called with the new text when the user types. It is a request, not a change.

So you need state that holds the text, survives recomposition, and triggers a redraw when it changes:

var name by remember { mutableStateOf("") }

TextField(
    value = name,
    onValueChange = { name = it },
    label = { Text("Plant name") }
)
  • mutableStateOf("") creates observable state: when it changes, readers recompose.
  • remember keeps that state across recompositions. Without it, each recomposition would create a fresh empty state.
  • rememberSaveable does the same and also survives rotation, as you saw in the lifecycle section. For typed text, prefer it.

Because the value passes through your code, you can also shape it, for example onValueChange = { name = it.take(30) } to cap the length.

When state is kept in a parent and passed down as value plus a callback, the child is stateless and easy to reuse and preview. This pattern is called state hoisting.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.