Sub topic 2
Reading and controlling text with TextEditingController
This chapter assumes basic Dart syntax, nullable types, closures, and Flutter widgets such as StatefulWidget, setState, Column, and Scaffold.
A TextEditingController is an object that stores and controls the current text in a text input. Use it when you need to read the value, set a value from code, clear the field, or react to changes.
Creating and reading a controller
Create the controller as a field on your State object, not inside build. If you create it during every build, Flutter can lose the current text and selection.
import 'package:flutter/material.dart';
void main() {
runApp(const MaterialApp(home: NamePage()));
}
class NamePage extends StatefulWidget {
const NamePage({super.key});
@override
State<NamePage> createState() => _NamePageState();
}
class _NamePageState extends State<NamePage> {
final _nameController = TextEditingController();
int _characterCount = 0;
@override
void initState() {
super.initState();
_nameController.addListener(_updateCharacterCount);
}
void _updateCharacterCount() {
setState(() {
_characterCount = _nameController.text.characters.length;
});
}
void _showName() {
final name = _nameController.text.trim();
if (name.isNotEmpty) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Hello, $name!')),
);
}
}
@override
void dispose() {
_nameController.removeListener(_updateCharacterCount);
_nameController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Name')),
body: Padding(
padding: const EdgeInsets.all(16),
child: Column(
children: [
TextField(
controller: _nameController,
decoration: const InputDecoration(labelText: 'Your name'),
),
const SizedBox(height: 8),
Text('Characters: $_characterCount'),
Row(
children: [
ElevatedButton(
onPressed: _showName,
child: const Text('Show name'),
),
const SizedBox(width: 8),
TextButton(
onPressed: _nameController.clear,
child: const Text('Clear'),
),
],
),
],
),
),
);
}
}controller.text reads the current value. The clear() method removes it. Assigning to controller.text replaces the value:
_nameController.text = 'Ada Lovelace';A controller also stores the selection and composing region. Assigning new text can change the cursor position, so use the controller's value when you need precise selection control.
Listening to changes
You can react to every edit in two common ways:
- Use
onChangedfor a small, local callback. - Use
addListenerwhen several methods need access to changes or when the controller is shared by other logic.
The listener receives no text argument. Read the latest value from _nameController.text. Remove the listener and dispose of the controller when the state is destroyed.
Controller versus initialValue
Use TextField with a controller when code must read or change the text. For a fixed starting value that does not need later control, TextFormField can use initialValue instead. Do not provide both controller and initialValue to the same TextFormField.
Exercise
Why should a TextEditingController be created outside build, and which lifecycle method should release it?
Show answer
Create it outside build so the same controller preserves text and selection across rebuilds. Call its dispose method in the State object's dispose method.