In Flutter, TextEditingController and onChanged are two different approaches for handling text input, each with distinct use cases:

TextEditingController

TextEditingController is a controller class that manages the text being edited in a text field. It provides more comprehensive control over the text input.

Key features:

  • Allows you to programmatically set, get, and modify text
  • Provides selection control (cursor position, text selection)
  • Gives access to the current text value at any time
  • Can be used to clear text, set initial values, or format text
  • Requires manual disposal to prevent memory leaks

Example:

class MyWidget extends StatefulWidget {
  @override
  _MyWidgetState createState() => _MyWidgetState();
}

class _MyWidgetState extends State<MyWidget> {
  final TextEditingController _controller = TextEditingController();

  @override
  void dispose() {
    _controller.dispose(); // Important: dispose to prevent memory leaks
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return TextField(
      controller: _controller,
      decoration: InputDecoration(hintText: 'Enter text'),
    );
  }
}

onChanged

onChanged is a callback function that gets triggered every time the text in the field changes. It’s a simpler, more reactive approach.

Key features:

  • Immediately responds to text changes
  • Receives the current text value as a parameter
  • No need for manual disposal
  • Good for simple validation or real-time filtering
  • More functional programming approach

Example:

TextField(
  onChanged: (String value) {
    print('Current text: $value');
    // Handle text change
  },
  decoration: InputDecoration(hintText: 'Enter text'),
)

When to use which?

When to use which?

Use TextEditingController when:

  • You need to programmatically control the text (set, clear, format)
  • You need to access text value from multiple places in your code
  • You need cursor/selection control
  • You’re building complex forms
  • You need to persist text across widget rebuilds

Use onChanged when:

  • You only need to react to text changes
  • You’re doing simple validation or filtering
  • You want a more straightforward, callback-based approach
  • You don’t need to manipulate the text programmatically

Can you use both together?

Yes! You can use both approaches simultaneously:

final TextEditingController _controller = TextEditingController();

TextField(
  controller: _controller,
  onChanged: (String value) {
    // React to changes
    print('Text changed: $value');
  },
  decoration: InputDecoration(hintText: 'Enter text'),
)

This gives you the flexibility of programmatic control while also allowing you to react to changes in real-time.

Also Read

Also Read:

Flutter Theming

Need Help With Flutter Development?

Work with our skilled Flutter developers to accelerate your project and boost its performance.

Hire Flutter Developers

Support On Demand!

Related Q&A