Sub topic 1
Your first TextField
This chapter introduces TextField, the basic widget for typing text in Flutter. You will place one on screen, read what the user types, react to changes, and learn the errors that beginners hit most often. Controllers, decoration, and forms get their own chapters, so this one stays on the basics.
Prerequisites
This chapter assumes you already know:
- Basic Dart syntax, including nullable types (
String?) and closures. - Flutter widget basics:
StatelessWidget,StatefulWidget, andsetState. - Common layouts such as
ColumnandScaffold.
You need a Flutter project that runs on an emulator, a device, or the web. Every example uses package:flutter/material.dart.
What a TextField is
TextField is a Material widget that shows an editable line of text. It handles the cursor, text selection, the on-screen keyboard, copy and paste, and the platform's text editing behavior. It does not store your data in a way you can read directly. You get the text through callbacks or through a controller, which a later chapter covers.
The smallest usable field looks like this:
import 'package:flutter/material.dart';
void main() => runApp(const MaterialApp(
home: Scaffold(
body: Padding(
padding: EdgeInsets.all(16),
child: TextField(),
),
),
));Run it and you get an underlined field. Tap it and the keyboard opens. The field has no label and no way to hand its text to the rest of your app, so it is not yet useful.
Why TextField needs a bounded width
A TextField tries to be as wide as its parent allows. Inside a Row, the parent gives it unbounded width, and Flutter throws an error such as "InputDecorator cannot have an unbounded width". The fix is to give the field a width limit, usually with Expanded.
import 'package:flutter/material.dart';
class SearchRow extends StatelessWidget {
const SearchRow({super.key});
@override
Widget build(BuildContext context) {
return const Row(
children: [
Expanded(child: TextField()),
Icon(Icons.search),
],
);
}
}The same problem appears inside a ListTile trailing slot or any other unbounded horizontal space. Wrap the field in SizedBox(width: ...) or Expanded.
Reacting to text with callbacks
TextField offers three callbacks. They fire at different moments, and choosing the wrong one is a common source of bugs.
| Callback | Fires when | Receives |
|---|---|---|
| `onChanged` | The text changes after any edit, including typing, deleting, and pasting | The full current text |
| `onSubmitted` | The user presses the keyboard's action key (done, search, and so on) | The full current text |
| `onEditingComplete` | The same action key press, but with default behavior replaced by yours | Nothing |
onChanged gives you the whole string every time, not only the newly typed characters. The next example keeps a character count in state.
import 'package:flutter/material.dart';
class CharacterCounter extends StatefulWidget {
const CharacterCounter({super.key});
@override
State<CharacterCounter> createState() => _CharacterCounterState();
}
class _CharacterCounterState extends State<CharacterCounter> {
String _text = '';
@override
Widget build(BuildContext context) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
TextField(
onChanged: (value) => setState(() => _text = value),
onSubmitted: (value) => debugPrint('Submitted: $value'),
),
const SizedBox(height: 8),
Text('${_text.length} characters'),
],
);
}
}Each keystroke calls setState, which rebuilds this widget. For a small screen that is fine. For a large screen with many fields, rebuilding everything on each keystroke wastes work. A controller, covered next chapter, lets you read the text only when you need it.
How the pieces fit together
The diagram shows what happens between a keystroke and your code.
The field keeps its own text internally. Your onChanged handler observes that text. It does not feed the text back into the field.
Common configuration at a glance
A few constructor parameters shape the basic behavior. Later chapters cover most of them in depth. This table lists the ones you will touch first.
| Parameter | Effect | Default |
|---|---|---|
| `autofocus` | Focuses the field and opens the keyboard when the screen appears | `false` |
| `enabled` | When `false`, the field ignores input and looks greyed out | `true` |
| `readOnly` | The field shows text and allows selection, but the user cannot edit it | `false` |
| `maxLines` | Number of visible lines. Use `null` for a field that grows without limit | `1` |
| `minLines` | Minimum lines for a growing field | none |
| `maxLength` | Maximum characters, with a counter shown under the field | none |
| `textCapitalization` | Keyboard capitalization hint, such as `TextCapitalization.sentences` | `none` |
Here is a multi-line notes field that uses several of them:
import 'package:flutter/material.dart';
class NotesField extends StatelessWidget {
const NotesField({super.key});
@override
Widget build(BuildContext context) {
return const TextField(
minLines: 3,
maxLines: 8,
maxLength: 280,
textCapitalization: TextCapitalization.sentences,
decoration: InputDecoration(
labelText: 'Notes',
border: OutlineInputBorder(),
),
);
}
}The decoration parameter adds a label and a border. A later chapter explains InputDecoration fully. It is shown here because an undecorated field is hard to see on a form.
Edge cases and errors to expect
These problems come up often when someone writes their first field.
- Unbounded width. A field inside a
Rowfails to lay out. Wrap it inExpanded. - Unbounded height. A
TextFieldwithmaxLines: nullinside aColumnthat sits in a scrolling parent can fail with a viewport height error. Give the field a bounded height or let the parent size it withExpanded. - Keyboard covers the field. On small screens the keyboard can hide the field. A
Scaffoldresizes its body when the keyboard opens, so keep the field inside theScaffoldbody, and place the form inside aSingleChildScrollViewwhen it has many fields. - Using
onChangedto store text you never display. If you only need the text at submit time,setStateon every keystroke does needless work. Use a controller instead. - Treating
onSubmittedas "the user is done". The user can leave a field by tapping elsewhere without pressing the action key.onSubmitteddoes not fire in that case. - Setting
readOnlyversusenabled. A disabled field is greyed out and cannot be selected. A read-only field looks normal and lets the user copy its text. Choose by what the user needs to do.
Putting it together
This small screen combines the pieces from this chapter. It shows a live preview of what the user types, and it resets the preview when the user submits.
import 'package:flutter/material.dart';
void main() => runApp(const MaterialApp(home: GreetingScreen()));
class GreetingScreen extends StatefulWidget {
const GreetingScreen({super.key});
@override
State<GreetingScreen> createState() => _GreetingScreenState();
}
class _GreetingScreenState extends State<GreetingScreen> {
String _name = '';
String _lastSubmitted = '';
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Greeting')),
body: Padding(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
TextField(
autofocus: true,
textCapitalization: TextCapitalization.words,
textInputAction: TextInputAction.done,
decoration: const InputDecoration(
labelText: 'Your name',
border: OutlineInputBorder(),
),
onChanged: (value) => setState(() => _name = value),
onSubmitted: (value) => setState(() {
_lastSubmitted = value.trim();
_name = '';
}),
),
const SizedBox(height: 16),
Text('Typing: $_name'),
if (_lastSubmitted.isNotEmpty) Text('Hello, $_lastSubmitted!'),
],
),
),
);
}
}Run it and type a name. The "Typing" line updates on each keystroke. Press the done key and the greeting appears. Note that the field itself still shows the typed text after submit, even though _name was reset to an empty string. Resetting the variable does not change what the field displays, because the field owns its text. Clearing the field needs a controller, which is the next chapter's subject.
Exercise
A TextField sits directly inside a Row and the app throws an error about unbounded width. What is the cause, and what is the smallest fix?
Show answer
A Row gives its children unbounded horizontal space, and a TextField tries to fill all available width, so it cannot compute a size. Wrap the TextField in Expanded (or a SizedBox with a fixed width) so it receives a bounded width.
Exercise
In the GreetingScreen example, onSubmitted sets _name to an empty string, yet the text stays visible in the field. Why, and what will you need to clear it?
Show answer
The TextField keeps its own internal text. onChanged only reports that text to your state, and changing your variable does not write back into the field. To clear the field you need a TextEditingController and a call such as controller.clear(), which the next chapter covers.
Exercise
Which callback receives the text when the user presses the keyboard's action key, and why is it unreliable as the only way to capture the final value?
Show answer
onSubmitted receives it. It is unreliable alone because the user can move away from the field by tapping elsewhere or switching screens without pressing the action key, and in that case onSubmitted never fires.