Answer
Overview
is a controller for editable text fields. It lets you read, write, and listen to changes in a textTextEditingController
text
TextFieldtext
TextFormFieldBasic Usage
dartclass MyForm extends StatefulWidget { _MyFormState createState() => _MyFormState(); } class _MyFormState extends State<MyForm> { final TextEditingController _controller = TextEditingController(); void dispose() { _controller.dispose(); // ✅ Always dispose to prevent memory leaks super.dispose(); } Widget build(BuildContext context) { return Column( children: [ TextField( controller: _controller, decoration: InputDecoration(labelText: 'Enter name'), ), ElevatedButton( onPressed: () { print('Input: ${_controller.text}'); // Read value }, child: Text('Submit'), ), ], ); } }
Reading & Writing Text
dart// Read current text String currentText = _controller.text; // Set text programmatically _controller.text = 'New Value'; // Set text and move cursor to end _controller.value = TextEditingValue( text: 'New Value', selection: TextSelection.collapsed(offset: 'New Value'.length), ); // Clear the field _controller.clear();
Listening to Changes
dartvoid initState() { super.initState(); _controller.addListener(() { print('Text changed: ${_controller.text}'); }); }
Pre-filling a TextField
dart// Pre-fill on creation final _controller = TextEditingController(text: 'Default Value'); // Or set it later _controller.text = 'Loaded from API';
With TextFormField & Validation
dartfinal _formKey = GlobalKey<FormState>(); final _emailController = TextEditingController(); Form( key: _formKey, child: TextFormField( controller: _emailController, validator: (value) { if (value == null || !value.contains('@')) { return 'Please enter a valid email'; } return null; }, ), ) // On submit if (_formKey.currentState!.validate()) { print('Email: ${_emailController.text}'); }
Multiple Controllers
dartfinal _nameController = TextEditingController(); final _emailController = TextEditingController(); final _passwordController = TextEditingController(); void dispose() { _nameController.dispose(); _emailController.dispose(); _passwordController.dispose(); super.dispose(); }
Key Properties
| Property | Description |
|---|---|
text | Get or set the text content |
text | Get or set cursor/selection position |
text | Full value including text and selection |
text | Listen to any changes |
text | Clear all text |
text | Release resources |
Important: Always call
on yourtextdispose()in the widget'stextTextEditingControllermethod to avoid memory leaks.textdispose()