FlutterBasic 2 min read

Flutter TextField and TextEditingController ownership

Read a text field, choose between onChanged and a controller, and dispose resources in the widget that creates them.

On this page

Use onChanged when you only need the latest text as the user types. Use a TextEditingController when the feature must read, prefill, clear or otherwise manipulate editing state programmatically.

Establish an owner

A State object can create a controller once and dispose it when the screen leaves the tree. Creating a new controller inside build can reset editing state and leave resources without a clear lifecycle.

Treat editing text as input

Trim only when the field’s meaning permits it. An email field and a free-form note have different whitespace rules. Validation should describe the real input requirement rather than applying a universal cleanup operation.

Worked example

This is a focused code fragment. Place it in the class or file described above; it is not a complete standalone app.

final titleController = TextEditingController();

void saveTitle() {
  final title = titleController.text.trim();
  if (title.isEmpty) return;
  // Pass title to the feature's state owner.
}

@override
void dispose() {
  titleController.dispose();
  super.dispose();
}

Read the result

These members belong in a State class. Connect the controller to TextField(controller: titleController). Keep network requests out of a listener that fires on every keystroke unless you add deliberate debouncing and cancellation.

Distinguish an editing buffer from saved domain data

The controller holds the text currently being edited. That may contain leading spaces, an incomplete number or an invalid project name. The saved model should receive data only after the feature’s validation rules accept it.

Reading text on every keystroke can be useful for a local preview. Starting a network request on every listener notification is a different decision and needs debouncing, stale-response handling and a clear lifetime. Do not hide those responsibilities inside a seemingly simple controller callback.

The State that creates the controller disposes it. If a parent owns the controller, the child should not assume ownership and dispose it independently. Follow the lifecycle guide and then build a validated form where invalid editing text remains separate from an accepted value.

Practice and verification

Create a prefilled title field, a Clear button and a Save action. Navigate away and back. Decide whether the draft should be screen-local or preserved by a longer-lived feature model.

How this topic connects

Understand first

Apply it next

Lesson progressMark complete after checking the example and exercise.

Find your next idea

Search lessons, code examples and projects.

Type a few words to start exploring.