TextEditingController

A controller for an editable text field. Whenever the user modifies a text field with an associated TextEditingController, the text field updates value and the controller notifies its listeners. Listeners can then read the text and selection properties to learn what the user has typed or how the selection has been updated.

Similarly, if you modify the text or selection properties, the text field will be notified and will update itself appropriately.

A TextEditingController can also be used to provide an initial value for a text field. If you build a text field with a controller that already has text, the text field will use that text as its initial value.

Remember to dispose of the TextEditingController when it is no longer needed. This will ensure we discard any resources used by the object.

The following example creates a TextField with a TextEditingController whose change listener forces the entered text to be lower case and keeps the cursor at the end of the input.

final _controller = TextEditingController();

void initState() {
  super.initState();
  _controller.addListener(() {
    final text = _controller.text.toLowerCase();
    _controller.value = _controller.value.copyWith(
      text: text,
      selection: TextSelection(baseOffset: text.length, extentOffset: text.length),
      composing: TextRange.empty,
    );
  });
}

void dispose() {
  _controller.dispose();
  super.dispose();
}

Widget build(BuildContext context) {
  return Scaffold(
    body: Container(
     alignment: Alignment.center,
      padding: const EdgeInsets.all(6),
      child: TextFormField(
        controller: _controller,
        decoration: InputDecoration(border: OutlineInputBorder()),
      ),
    ),
  );
}

Properties

selection

The currently selected text. The type of the value is TextSelection. We will learn about this later on.

value

The current value stored in this notifier. The type of the value is TextEditingValue. We will learn more about this later on.

text

This represents the text string that is present in the textbox. The following statement updates the textbox dynamically

_controller.text = "Hello World";

Methods

clear()

Set the value to empty.

addListener(callback)

Register a closure to be called when the object changes.

dispose()

Discards any resources used by the object.