Sub topic 2
Reading and controlling text with TextEditingController
This chapter assumes you can write a StatefulWidget and use initState and dispose. It also assumes you know Dart's nullable types and closures, and that you have built a basic TextField in the previous chapter. Here you will learn what a TextEditingController holds, how to read and change the text, how to react to edits, and how to avoid the common lifecycle mistakes.
What a controller holds
A TextEditingController is a ChangeNotifier that stores a TextEditingValue. That value has three parts:
text: the current string.selection: the caret position or the selected range.composing: the range the keyboard is still composing, for example while typing with an input method editor.
The field reads from the controller when it builds, and it writes back to the controller on every edit. Because the controller is a ChangeNotifier, anything that listens to it is told whenever the text, the caret, or the selection changes.
Creating and disposing a controller
A controller allocates resources and keeps a list of listeners, so it has a lifecycle. The State object that owns the controller creates it once and disposes it once.
import 'package:flutter/material.dart';
void main() => runApp(
const MaterialApp(home: Scaffold(body: NameField())),
);
class NameField extends StatefulWidget {
const NameField({super.key});
@override
State<NameField> createState() => _NameFieldState();
}
class _NameFieldState extends State<NameField> {
final _controller = TextEditingController();
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.all(16),
child: Column(
children: [
TextField(
controller: _controller,
decoration: const InputDecoration(labelText: 'Name'),
),
ElevatedButton(
onPressed: () => debugPrint('Name: ${_controller.text}'),
child: const Text('Print'),
),
],
),
);
}
}The controller is a field of the State, not a local variable inside build. build can run many times per second. A controller created there would be replaced on every rebuild, and the user's text and caret would be lost.
You can give the controller starting text with TextEditingController(text: 'Ada'). For a field that starts empty, no argument is needed.
Reading the text
There are two ways to read what the user typed.
| Approach | When it runs | Best for |
|---|---|---|
| `controller.text` | When you ask for it | Reading on a button press or at submit time |
| `onChanged` callback | On every user edit | Reacting to each keystroke without a controller |
Prefer reading controller.text at the moment you need it, such as in a submit handler. That avoids copying the value into a separate state variable that can fall out of sync. onChanged fires only for edits made by the user. Changing controller.text from code does not call onChanged. If you need to react to every change, including ones your code makes, listen to the controller.
Changing the text from code
You can assign to text to replace the contents, or call clear() to empty the field.
_controller.text = 'Ada Lovelace';
_controller.clear();Assigning text has a side effect that surprises people. The selection is reset, so the caret is no longer at a valid position. For a field the user will keep editing, set the whole value and place the caret yourself.
void _setEmail(String email) {
_controller.value = TextEditingValue(
text: email,
selection: TextSelection.collapsed(offset: email.length),
);
}TextSelection.collapsed(offset: n) puts the caret at position n with nothing selected. Use email.length to place it at the end. To select a range, for example so the user can overwrite the text, use TextSelection(baseOffset: 0, extentOffset: email.length).
Reacting to changes with a listener
Because the controller is a ChangeNotifier, you can call addListener. The listener runs when the text, selection, or composing range changes, so it also runs when the user only moves the caret.
class _CounterFieldState extends State<CounterField> {
final _controller = TextEditingController();
int _length = 0;
@override
void initState() {
super.initState();
_controller.addListener(_onTextChanged);
}
void _onTextChanged() {
if (_controller.text.length != _length) {
setState(() => _length = _controller.text.length);
}
}
@override
void dispose() {
_controller.removeListener(_onTextChanged);
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.all(16),
child: Column(
children: [
TextField(controller: _controller),
Text('$_length characters'),
],
),
);
}
}
class CounterField extends StatefulWidget {
const CounterField({super.key});
@override
State<CounterField> createState() => _CounterFieldState();
}The if check matters. Without it, setState would run when the user only moves the caret, which rebuilds the widget for no reason. Call addListener in initState, not in build, or you will add a new listener on every rebuild.
Rebuilding only what depends on the text
TextEditingController is a ValueListenable<TextEditingValue>. That lets you skip the listener and setState entirely and rebuild only a small part of the tree.
ValueListenableBuilder<TextEditingValue>(
valueListenable: _controller,
builder: (context, value, child) {
return ElevatedButton(
onPressed: value.text.trim().isEmpty ? null : _submit,
child: const Text('Save'),
);
},
)Here the button is disabled while the field is empty. Only the button rebuilds when the text changes, and the surrounding form does not. ValueListenableBuilder removes its own listener, so there is nothing extra to clean up.
Ownership and common errors
The rule is that whoever creates the controller disposes it. A controller you receive as a constructor argument belongs to the caller, so do not dispose it in your widget.
| Mistake | Symptom | Fix |
|---|---|---|
| Creating the controller in `build` | Text or caret resets while typing | Create it once as a `State` field |
| Not calling `dispose()` | Memory leak, leak warnings in debug | Dispose in `State.dispose` |
| Using a controller after disposing it | "used after being disposed" error | Do not touch it after `dispose`, and guard async callbacks with `if (!mounted) return;` |
| Sharing one controller across two fields | Both fields show the same text | Use one controller per field |
| Passing both `controller` and `initialValue` to `TextFormField` | Assertion error | Use the controller's `text` for the starting value |
| Assigning `text` and expecting `onChanged` to fire | Handler never runs | Listen to the controller instead |
The last row of the lifecycle problems appears in async code. If a request finishes after the user has left the screen, the State is already disposed. Check mounted before you read or change the controller.
Future<void> _loadProfile() async {
final name = await fetchName(); // your own async function
if (!mounted) return;
_controller.text = name;
}When you do not need a controller
A controller is not required for every field. If you only want the final value when the form is submitted, a Form with onSaved callbacks does that without a controller, and you will see it in a later chapter. Use a controller when you need to read the text at arbitrary times, set it from code, react to each change, or compare it with another field. Fewer controllers means fewer things to dispose.
Exercise
A TextField has a TextEditingController. When the user taps a "Use my email" button, you run _controller.text = '[email protected]';. The text appears, but the user cannot continue typing from the end of it, and an onChanged handler on the field never runs. Explain why both things happen, and show how to fix the caret problem.
Show answer
Assigning text replaces the value and resets the selection, so the caret is not at a valid position at the end. onChanged only fires for edits made by the user, not for changes made from code. To fix the caret, set the whole value: _controller.value = TextEditingValue(text: email, selection: TextSelection.collapsed(offset: email.length));. If code must react to programmatic changes, add a listener with _controller.addListener(...) or wrap the dependent widget in a ValueListenableBuilder<TextEditingValue>.
Exercise
You write TextEditingController _c = TextEditingController(); as a local variable at the top of build in a StatefulWidget. Name two problems this causes and where the controller should live instead.
Show answer
The controller is recreated on every rebuild, so typed text and caret position are lost, and the old controllers are never disposed, which leaks them. Declare it as a field of the State class, create it once, and call dispose() on it in State.dispose.