DEV Community

Cover image for Taking Over the Keyboard: Moving Compose Text Fields to TextFieldState
Android Expert
Android Expert

Posted on Originally published at Medium

Taking Over the Keyboard: Moving Compose Text Fields to TextFieldState

If you open a Compose codebase that is a couple of years old and search for onValueChange, you will probably get hundreds of hits, and a growing number of them are tagged with deprecation warnings. The callback-based overloads are being phased out: the value/onValueChange versions of BasicTextField are deprecated in favor of BasicTextField(state: TextFieldState, ...), and as of Compose 1.13 the Material wrappers (Material 2 and Material 3) follow the same direction with soft deprecation. The surrounding APIs (TextFieldState, InputTransformation, OutputTransformation, TextFieldLineLimits, the decorator) have graduated to stable.

This post is a field guide for doing that migration without shipping a regression: why the old model was retired, what the new code looks like, how transformations change, what you get for free (undo/redo), a checklist, and the traps that tend to bite teams in review.

1. Why value-based fields were retired

A value-based field is a conversation between two parties. The platform (IME, hardware keyboard, accessibility service) says “the text is now X,” and your code answers by feeding a new value back in on the next composition.

why-state-based

That arrangement has three structural problems.

Ownership is split. The text lives in your variable, but the selection and the IME composition region live inside the field. Every time they disagree, even for a frame, you can see dropped characters or a cursor that jumps to the end. The classic repro is “format as the user types” logic inside onValueChange: you rewrite the string, the field's cursor no longer lines up, and fast typists feel it.

Correctness depends on your update being immediate. The field applies the IME edit to its own buffer first and then reports it through onValueChange. As long as you write the new value back right away, everything agrees. The trouble starts when you do not: rewriting the string, debouncing it, moving it through a ViewModel coroutine, or skipping a recomposition leaves the value you pass in disagreeing with what the field already holds. The state-based API removes the callback entirely, so there is no round trip in the input path to get wrong.

Persistence and richer behavior were bolted on. rememberTextFieldState() comes with save and restore built in, and the state object carries text, selection and undo history together. Features like change tracking and styled output are modeled on a buffer the field owns, rather than on a string you hand back and forth.

The mental shift: you stop feeding the field and start holding its state. One caveat: removing the callback does not make the state thread-safe. If you mutate a TextFieldState from a background coroutine while the user is typing, you can still race with IME edits, so do programmatic edits on the main thread.

2. Before and after for a basic field

Here is a typical value-based field with a length cap:

@Composable
fun HandleField(modifier: Modifier = Modifier) {
    var handle by rememberSaveable { mutableStateOf("") }

    BasicTextField(
        value = handle,
        onValueChange = { handle = it.take(20) },
        modifier = modifier,
        singleLine = true,
    )
}
Enter fullscreen mode Exit fullscreen mode

And the state-based version:

@Composable
fun HandleField(modifier: Modifier = Modifier) {
    val handle = rememberTextFieldState()

    BasicTextField(
        state = handle,
        modifier = modifier,
        lineLimits = TextFieldLineLimits.SingleLine,
        inputTransformation = InputTransformation.maxLengthTrim(20),
    )
}
Enter fullscreen mode Exit fullscreen mode

Three things changed at once: the string variable became a state object, the filtering moved out of the callback into a declared transformation, and singleLine became lineLimits.

For Material 3, the shape is the same:

OutlinedTextField(
    state = handle,
    label = { Text("Handle") },
    lineLimits = TextFieldLineLimits.SingleLine,
    inputTransformation = InputTransformation.maxLengthTrim(20),
)
Enter fullscreen mode Exit fullscreen mode

Reading and writing the text programmatically goes through the state:

val current: String = handle.text.toString()

handle.setTextAndPlaceCursorAtEnd("kotlin_dev")   // replace and place cursor
handle.edit { append("_2026") }                   // fine-grained edits
handle.clearText()
Enter fullscreen mode Exit fullscreen mode

3. From VisualTransformation to Input and Output transformations

VisualTransformation did two jobs in one function: it decided what text was accepted (indirectly, via your onValueChange) and how it was displayed, and it demanded an OffsetMapping so the cursor could travel between the raw and displayed strings. Getting the mapping wrong is one of the most common sources of crashes and wandering cursors in custom formatters.

The new model splits the job and removes the mapping.

transformation-pipeline

  • InputTransformation runs after each user change and can rewrite or reject it. Whatever survives is what gets stored.
  • OutputTransformation only decorates what is drawn. The stored text is untouched, and you do not provide an offset map.

A digits-only phone field

private val phoneInput = InputTransformation
    .byValue { _, proposed -> proposed.filter(Char::isDigit) }
    .maxLengthReject(10)

private val phoneOutput = OutputTransformation {
    val digits = length                 // length before we insert anything
    if (digits > 0) insert(0, "(")
    if (digits > 3) insert(4, ") ")
    if (digits > 6) insert(9, "-")
}

@Composable
fun PhoneField(state: TextFieldState) {
    BasicTextField(
        state = state,
        keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),
        lineLimits = TextFieldLineLimits.SingleLine,
        inputTransformation = phoneInput,
        outputTransformation = phoneOutput,
    )
}
Enter fullscreen mode Exit fullscreen mode

state.text holds 5551234567, while the screen shows (555) 123-4567. Your ViewModel never has to strip punctuation. Note the index math: each insert shifts later positions, which is why the indices climb as 0, 4, 9.

Custom input rules

For rules that do not fit byValue, implement the interface directly. InputTransformation is a single-function interface that operates on a TextFieldBuffer:

val noWhitespace = InputTransformation {
    if (asCharSequence().any(Char::isWhitespace)) revertAllChanges()
}
Enter fullscreen mode Exit fullscreen mode

Chain filters with then, in the order you want them to run:

val slugInput = InputTransformation
    .byValue { _, proposed -> proposed.toString().lowercase() }
    .then(noWhitespace)
    .maxLengthTrim(40)
Enter fullscreen mode Exit fullscreen mode

The length filters: trim versus reject

The old InputTransformation.maxLength(n) is deprecated in favor of two explicit variants, and the difference matters most when users paste.

length-filters

  • maxLengthTrim(n) keeps what fits and drops the excess characters. This is friendly for free-form text such as bios or captions.
  • maxLengthReject(n) reverts the entire edit if it would exceed the limit. This suits structured values (postal codes, OTPs, IDs) where a partially pasted value is worse than no value.

One accessibility detail: when an OutputTransformation adds decoration characters, the maximum length announced to screen readers may no longer match what users perceive. In that case, set maxTextLength in a custom transformation's semantics rather than relying on the built-in filter alone.

Passwords

PasswordVisualTransformation goes away with the rest of the visual transformations. Use the dedicated secure fields (SecureTextField in Material 3 or BasicSecureTextField in Foundation) instead of wiring obfuscation yourself.

4. Undo/redo and change tracking

Because the state owns the edit history, undo and redo cost almost nothing to add:

@Composable
fun NoteEditor() {
    val note = rememberTextFieldState()

    Column {
        Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
            Button(onClick = { note.undoState.undo() }, enabled = note.undoState.canUndo) { Text("Undo") }
            Button(onClick = { note.undoState.redo() }, enabled = note.undoState.canRedo) { Text("Redo") }
            Button(
                onClick = { note.undoState.clearHistory() },
                enabled = note.undoState.canUndo || note.undoState.canRedo,
            ) { Text("Clear") }
        }
        BasicTextField(state = note, modifier = Modifier.fillMaxWidth())
    }
}
Enter fullscreen mode Exit fullscreen mode

undo-redo-timeline

canUndo and canRedo are backed by snapshot state, so the buttons enable and disable themselves without any extra plumbing. Undo reverts the most recent edit or a group of merged edits, so typing a word is not undone one letter at a time. Call clearHistory() when you load a new document into the same state, otherwise users can "undo" into the previous file.

For change tracking, an InputTransformation can inspect exactly what changed in the current edit:

import androidx.compose.foundation.text.input.forEachChange
import androidx.compose.ui.text.substring   // CharSequence.substring(TextRange)

val auditing = InputTransformation {
    changes.forEachChange { range, originalRange ->
        val inserted = asCharSequence().substring(range)
        Log.d("Field", "${originalRange.length} chars replaced by \"$inserted\"")
    }
}
Enter fullscreen mode Exit fullscreen mode

range is where the change landed in the edited buffer, and originalRange is the span it replaced in the text before the edit. Both are TextRange values, and forEachChange is an extension function, so it needs its own import. Depending on your Foundation version it may still carry an experimental opt-in, so check the compiler output.

This is far more precise than diffing old and new strings yourself, and it makes things like “flag edits that touched the first line” or “ignore pure cursor moves” straightforward.

5. Migration checklist for Material 2 and Material 3 users

migration-map

Everyone

  1. Raise Foundation and your Material artifact to versions that carry the state overloads (the callback overloads are soft-deprecated from Compose 1.13), then clear the deprecation warnings module by module.
  2. Replace var text by remember { mutableStateOf("") } with rememberTextFieldState() (or a hoisted TextFieldState).
  3. Move filtering out of onValueChange into InputTransformation.
  4. Move display formatting into OutputTransformation and delete the OffsetMapping code.
  5. Swap singleLine/maxLines/minLines for lineLimits, and keyboardActions for onKeyboardAction.
  6. Replace password transformations with the secure text field components.
  7. Add or update UI tests: assert on state.text, not on a string you kept on the side.

Material 3 users can usually stay on TextField or OutlinedTextField and switch to the state overload. Parameters you rely on (label, supporting text, icons, colors) carry over, and Material 3 adds options such as labelPosition.

Material 2 users do not have to move to Material 3 to adopt TextFieldState. The M2 TextField and OutlinedTextField also have state overloads, with the callback versions soft-deprecated alongside them. That means the text-field migration and any Material 3 migration are independent projects: do the state migration first inside M2, ship it, and treat the design-system move as a separate pull request.

6. Common pitfalls

pitfalls

Creating state without remembering it

// Bug: a fresh state on every recomposition. Typing appears to "do nothing".
val state = TextFieldState(initialText)

// Better, but not enough for screens that must survive rotation:
val state = remember { TextFieldState(initialText) }

// Fix: remembered and saved across configuration change and process recreation
val state = rememberTextFieldState(initialText)
Enter fullscreen mode Exit fullscreen mode

Plain remember { } survives recomposition only. It is lost when the activity is recreated (rotation, for example), which is why the saveable variant is the default to reach for.

Hoisting the string instead of the state

Passing state.text.toString() into a child composable and creating a new TextFieldState there reintroduces the split-ownership problem. Pass the TextFieldState itself, and let the child read from it.

Reading state.text in the composable body

Reading text during composition subscribes that scope to every keystroke. If you only need it for an enabled flag or a counter, read inside a lambda, derive with derivedStateOf, or collect through snapshotFlow.

ViewModel integration

Holding a TextFieldState in a ViewModel is a supported pattern, and it keeps the field's selection and history across configuration changes. What it does not do on its own is survive process death, because a ViewModel is not saved. A pragmatic pattern is to seed from SavedStateHandle and mirror changes back:

class SignUpViewModel(private val handle: SavedStateHandle) : ViewModel() {

    val email = TextFieldState(handle.get<String>("email").orEmpty())

    val canSubmit: StateFlow<Boolean> = snapshotFlow { email.text.toString() }
        .map { it.contains('@') && it.length > 5 }
        .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), false)

    init {
        viewModelScope.launch {
            snapshotFlow { email.text.toString() }
                .drop(1)
                .collect { handle["email"] = it }
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

This restores the text only. If you also want the selection back, store the state object itself with TextFieldState.Saver through the SavedStateHandle.saveable API instead of writing a string by hand:

class SignUpViewModel(handle: SavedStateHandle) : ViewModel() {
    // Restores via TextFieldState.Saver; no manual handle["email"] = ... needed.
    val email: TextFieldState = handle.saveable(
        key = "email",
        saver = TextFieldState.Saver,
    ) { TextFieldState() }
}
Enter fullscreen mode Exit fullscreen mode

Never put a TextFieldState straight into handle["key"], because it is not a bundle-friendly type. What Saver restores (text and selection for sure, undo history depending on version) should be covered by a restoration test rather than assumed. And since snapshotFlow emits on every change, debounce it before calling a network validator.

Assuming edit { } is filtered

Programmatic edits do not pass through InputTransformation. If your ViewModel sets text from a deep link or a clipboard helper, validate it there too, or you will store values the field would have rejected.

Forgetting that output changes layout, not data

Anything you add in OutputTransformation is invisible to state.text. That is the point, but it surprises teams who then try to read the formatted phone number back out of the state for submission.

Wrapping up

The migration looks mechanical, but the real win is conceptual: one object owns text, selection and history, filters declare intent instead of rewriting strings in callbacks, and display formatting no longer requires hand-built offset maps. Migrate one field type at a time, start with the simplest forms, and keep an eye on the three failure modes that cause most incidents: unremembered state, unsaved ViewModel state, and unvalidated programmatic edits.

Further reading

📱 Go Beyond Using AI — Learn How to Actually Build It Into Your Android Apps

If you’re building Android apps in 2026, “adding AI” can’t just mean bolting on a chatbot API — it means understanding on-device inference, model trade-offs, and production realities well enough to ship a feature users actually trust. I highly recommend “Mastering Android AI: App to Intelligence” It’s a practical, code-first journey through the entire Android AI stack — from ML Kit and LiteRT to Gemma, Gemini, and MediaPipe — covering everything from your first “hello inference” screen to thermal throttling, model drift monitoring, and full applied projects like an AI-powered camera app and a health companion, with hands-on Kotlin builds at every step.

Top comments (0)