CodeBlanks Logo Icon CodeBlanks

TextEditingController

Control input with TextEditingController.

What is TextEditingController?

TextEditingController is a controller that lets you read and change the text inside a TextFormField from outside. You create the controller and pass it to the controller parameter of TextFormField. You can then access its text via controller.text.

final controller = TextEditingController();

TextFormField(
  controller: controller,
)

The dispose method

A controller must be disposed when it is no longer used; this prevents memory leaks. In stateful widgets, this is usually done in the State's dispose method by calling controller.dispose().

Practice Print text with a controller

In main, create a TextEditingController with text set to 'Merhaba'. Print the value of controller.text with print. Wire it as controller to the TextFormField.

Starter code

main.dart
import 'package:flutter/material.dart';

// Burada TextEditingController olustur, text degerini 'Merhaba' yap

void main() {
  // print ile controller.text yazdir
  runApp(const Uygulama());
}

class Uygulama extends StatelessWidget {
  const Uygulama({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: Center(
          child: TextFormField(
            // controller parametresini ekle
          ),
        ),
      ),
    );
  }
}

Sample solution

main.dart
import 'package:flutter/material.dart';

final controller = TextEditingController(text: 'Merhaba');

void main() {
  print(controller.text);
  runApp(const Uygulama());
}

class Uygulama extends StatelessWidget {
  const Uygulama({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: Center(
          child: TextFormField(
            controller: controller,
          ),
        ),
      ),
    );
  }
}

Expected output

Merhaba

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 How do you access the text held by a TextEditingController?

  • controller.string
  • controller.value
  • controller.input
  • controller.text Correct answer

Explanation: The controller's text is accessed via the .text property; .value returns a TextEditingValue, and .input or .string do not exist.

2 Add the controller parameter

Question
TextFormField(
  ____: myController,
)
Answer
TextFormField(
  controller: myController,
)

Explanation: To wire a controller to TextFormField, the controller parameter is used; text, value or content are not parameters.

3 Controller parts

Term Meaning
TextEditingController Class that controls the text
controller Parameter wired to TextFormField
text Text property on the controller
dispose Method that cleans up the controller

All lessons in Beginner