Flutter TextField & Forms
Almost every app needs to collect input: a search box, a login screen, a note editor. In Flutter, the basic building block for text input is the TextField widget. When you have several fields that must be checked together, you wrap them in a Form and use TextFormField, which adds built-in validation.
A simple TextField
A TextField shows an editable line of text. Its look is controlled by an InputDecoration, which can add a label, hint text, icons, a border and an error message.
import 'package:flutter/material.dart';
void main() => runApp(const MaterialApp(home: NameScreen()));
class NameScreen extends StatelessWidget {
const NameScreen({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Your name')),
body: const Padding(
padding: EdgeInsets.all(16),
child: TextField(
decoration: InputDecoration(
labelText: 'Name',
hintText: 'e.g. Ada Lovelace',
prefixIcon: Icon(Icons.person),
border: OutlineInputBorder(),
),
),
),
);
}
}Reading the text with a controller
To read or change what the user typed, give the field a TextEditingController. Controllers hold state, so you create them inside a State object and dispose of them when the widget goes away.
class GreetingForm extends StatefulWidget {
const GreetingForm({super.key});
@override
State<GreetingForm> createState() => _GreetingFormState();
}
class _GreetingFormState extends State<GreetingForm> {
final _controller = TextEditingController();
String _greeting = '';
@override
void dispose() {
_controller.dispose(); // free the resources
super.dispose();
}
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.all(16),
child: Column(
children: [
TextField(
controller: _controller,
decoration: const InputDecoration(labelText: 'Name'),
),
const SizedBox(height: 12),
FilledButton(
onPressed: () {
setState(() => _greeting = 'Hello, ${_controller.text}!');
debugPrint('Typed: ${_controller.text}');
},
child: const Text('Greet me'),
),
const SizedBox(height: 12),
Text(_greeting, style: const TextStyle(fontSize: 20)),
],
),
);
}
}Typed: Mia
Instead of a button you can also react on every keystroke with onChanged: (value) { ... }, or when the user presses the keyboard's done key with onSubmitted.
Useful TextField options
| Property | What it does |
|---|---|
keyboardType |
Which keyboard to show, e.g. TextInputType.emailAddress, TextInputType.number |
obscureText: true |
Hides the characters (passwords) |
maxLines |
1 by default; null lets the field grow |
maxLength |
Limits input and shows a counter |
textInputAction |
The keyboard's action button: next, done, search … |
autofocus: true |
Focuses the field when the screen opens |
Forms and validation
A Form groups TextFormFields. Each field gets a validator function that returns an error message (a String) when the value is invalid, or null when it is fine. You call validate() through a GlobalKey<FormState> to check all fields at once.
class SignUpForm extends StatefulWidget {
const SignUpForm({super.key});
@override
State<SignUpForm> createState() => _SignUpFormState();
}
class _SignUpFormState extends State<SignUpForm> {
final _formKey = GlobalKey<FormState>();
@override
Widget build(BuildContext context) {
return Form(
key: _formKey,
child: Padding(
padding: const EdgeInsets.all(16),
child: Column(
children: [
TextFormField(
decoration: const InputDecoration(labelText: 'Email'),
keyboardType: TextInputType.emailAddress,
validator: (value) {
if (value == null || value.isEmpty) return 'Please enter your email';
if (!value.contains('@')) return 'That does not look like an email';
return null;
},
),
TextFormField(
decoration: const InputDecoration(labelText: 'Password'),
obscureText: true,
validator: (value) =>
(value ?? '').length < 8 ? 'Use at least 8 characters' : null,
),
const SizedBox(height: 16),
FilledButton(
onPressed: () {
final ok = _formKey.currentState!.validate();
debugPrint('Form valid: $ok');
},
child: const Text('Sign up'),
),
],
),
),
);
}
}Form valid: false
When validate() returns true you can call _formKey.currentState!.save(), which runs every field's onSaved callback — a handy place to copy values into a model object.
Tip: Set
autovalidateMode: AutovalidateMode.onUserInteractionon theFormso errors appear while the user types, after they first touch a field.
Note: A validator returning
nullmeans "valid". Returning any string — even an empty one — marks the field as invalid.
Test yourself
What should a TextFormField validator return when the value is valid?
- true
- An empty string
- null
- The value itself
Why do you call _controller.dispose() in dispose()?
- To clear the text
- To release the controller's resources when the widget is removed
- To validate the field
- To hide the keyboard
Which property hides the characters typed into a password field?
- hidden: true
- password: true
- obscureText: true
- secure: true