Flutter's TextField: Capturing User Input
Flutter's TextField is the standard widget for user text input. Use it for search bars or login forms, and manage its state with a TextEditingController for full control. The biggest footgun is forgetting to dispose its controller, causing memory leaks.
WHY IT EXISTS Apps need a standard way to accept text from users via physical or on-screen keyboards. The TextField widget provides this fundamental building block, styled according to Material Design principles, for capturing any kind of text input.
THE MENTAL MODEL Think of a TextField as a stateful input box. You can either listen for changes passively with callbacks like onChanged and onSubmitted, or actively manage its state with a TextEditingController. The controller acts like a remote control for the text field's content, selection, and initial value.
HOW IT WORKS TextField renders an editable text area. When a user types, it fires the onChanged callback with the new string. When they signal completion (e.g., pressing 'done' on the keyboard), it calls onSubmitted. For robust control, you create a TextEditingController, pass it to the controller property, and later access its value with controller.text. You must call controller.dispose() in your StatefulWidget's dispose method to prevent memory leaks. A critical detail for handling user input: always use string.characters.length to measure length, as string.length will incorrectly count complex characters like emojis.
WHEN TO USE IT Use TextField for any form of user text input: search fields, message composition boxes, or simple data entry fields. Customize its appearance with the decoration property to add hints, labels, and icons. For password fields, simply set obscureText: true.
WHEN NOT TO USE IT If you need to validate input as part of a larger form with multiple fields, use TextFormField instead. TextFormField is a wrapper around TextField that integrates directly with Flutter's Form widget system, simplifying validation and state management across multiple inputs.
ONE CANONICAL EXAMPLE A login screen is a perfect example. You would use two TextFields, one for the username and one for the password. The password field would have obscureText: true. Both would use TextEditingControllers so you can read their values when the user taps a "Login" button. You would also call dispose() on both controllers when the screen is removed from the widget tree.
Read the original → api.flutter.dev
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.