Question #316EasyWidgets & UI

What is TextEditingController?

#widget#forms#input

Answer

Overview

text
TextEditingController
is a controller for editable text fields. It lets you read, write, and listen to changes in a
text
TextField
or
text
TextFormField
.


Basic Usage

dart
class 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

dart

void 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

dart
final _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

dart
final _nameController = TextEditingController();
final _emailController = TextEditingController();
final _passwordController = TextEditingController();


void dispose() {
  _nameController.dispose();
  _emailController.dispose();
  _passwordController.dispose();
  super.dispose();
}

Key Properties

PropertyDescription
text
.text
Get or set the text content
text
.selection
Get or set cursor/selection position
text
.value
Full value including text and selection
text
addListener()
Listen to any changes
text
clear()
Clear all text
text
dispose()
Release resources

Important: Always call

text
dispose()
on your
text
TextEditingController
in the widget's
text
dispose()
method to avoid memory leaks.