Sub topic 4
Configuring the keyboard and obscured text
This chapter assumes you can build a TextField with a TextEditingController and an InputDecoration, and that you know StatefulWidget and setState. It covers the properties that control the on-screen keyboard, the action key, masked input and autofill. Input formatters and focus movement get their own chapters.
What each property controls
Several properties on TextField and TextFormField shape the typing experience. Each one talks to a different part of the platform, and they are independent of each other.
| Property | What it decides |
|---|---|
| `keyboardType` | Which keyboard layout the OS shows |
| `textInputAction` | What the return/action key looks like and does |
| `textCapitalization` | Whether the keyboard auto-capitalizes |
| `autocorrect`, `enableSuggestions` | Whether the keyboard rewrites or suggests words |
| `obscureText` | Whether the field draws bullets instead of characters |
| `autofillHints` | What kind of data the OS may offer to fill in |
Keyboard type
keyboardType takes a TextInputType. Pick the one that matches the data.
| Value | Typical use |
|---|---|
| `TextInputType.text` | Default for general text |
| `TextInputType.emailAddress` | Email, with `@` and `.` within easy reach |
| `TextInputType.phone` | Phone numbers |
| `TextInputType.number` | Digits only, on most mobile keyboards |
| `TextInputType.url` | Web addresses, with `/` and `.com` keys |
| `TextInputType.multiline` | Multi-line text, where return inserts a newline |
| `TextInputType.visiblePassword` | A password keyboard that avoids suggestions, mainly useful on Android |
TextInputType.number shows a keypad without a minus sign or decimal point. For decimals or negative values, use the factory constructor:
TextFormField(
keyboardType: const TextInputType.numberWithOptions(
decimal: true,
signed: true,
),
decoration: const InputDecoration(labelText: 'Temperature'),
)Two related properties matter for text such as names and emails:
textCapitalizationacceptsTextCapitalization.none,.words,.sentencesor.characters. Use.wordsfor names and.nonefor emails and usernames.autocorrect: falsestops the keyboard from rewriting what the user typed. This helps for emails, usernames and codes.
Text input action
textInputAction sets the label or icon on the keyboard's action key. Common values are next, done, search, send and go. Use next on every field except the last, and done (or another terminal action) on the last field.
Two behaviors are easy to miss:
- With
TextInputAction.next, Flutter's default behavior moves focus to the next focusable widget when the key is pressed. You don't need aFocusNodefor the simple case. The Focus chapter covers cases where the default order is wrong. - The action key triggers
onFieldSubmittedon aTextFormField(onSubmittedon aTextField). This is where you call your submit method for the last field.
Obscured text
Setting obscureText: true makes the field draw each character as a bullet. You can change the bullet with obscuringCharacter, which must be a single character.
TextFormField(
obscureText: true,
obscuringCharacter: '*',
decoration: const InputDecoration(labelText: 'PIN'),
)Know these rules before you use it:
- The field must be single-line. Flutter asserts that
obscureTextis only used withmaxLines: 1, and the default is already 1. - On mobile, the most recently typed character is shown briefly before it turns into a bullet. This is standard platform behavior.
- Masking changes only what is drawn.
controller.textstill holds the plain value, so never print it, log it or put it in an error message. - Passwords should not be auto-corrected or suggested. Set
autocorrect: falseandenableSuggestions: falseexplicitly rather than relying on platform defaults. - Don't
trim()a password before validating or sending it. Spaces may be intentional.
A show/hide toggle
Users make fewer password mistakes when they can reveal the text. Keep a bool in State and flip it from a suffixIcon. The controller keeps its text when obscureText changes, so nothing is lost.
Autofill hints
autofillHints tells the OS what a field contains, so password managers and the keyboard can offer saved values. Use the constants in AutofillHints, such as email, username, password, newPassword, oneTimeCode, name, telephoneNumber and postalCode.
Wrap related fields in an AutofillGroup. The group lets the OS treat them as one credential set. When the form succeeds, call TextInput.finishAutofillContext() so the OS offers to save the credentials. To discard them instead, call TextInput.finishAutofillContext(shouldSave: false).
Use AutofillHints.newPassword on sign-up and password-change fields. It lets password managers suggest a strong password instead of filling in an old one.
A complete login form
This example combines everything above. It uses a minimal validator on each field, which the next chapters expand on.
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
void main() {
runApp(
const MaterialApp(
home: Scaffold(
body: Padding(
padding: EdgeInsets.all(16),
child: LoginForm(),
),
),
),
);
}
class LoginForm extends StatefulWidget {
const LoginForm({super.key});
@override
State<LoginForm> createState() => _LoginFormState();
}
class _LoginFormState extends State<LoginForm> {
final _formKey = GlobalKey<FormState>();
final _email = TextEditingController();
final _password = TextEditingController();
bool _hidePassword = true;
@override
void dispose() {
_email.dispose();
_password.dispose();
super.dispose();
}
String? _required(String? value) =>
(value == null || value.isEmpty) ? 'This field is required' : null;
void _submit() {
if (_formKey.currentState!.validate()) {
TextInput.finishAutofillContext();
debugPrint('Signing in ${_email.text}');
}
}
@override
Widget build(BuildContext context) {
return Form(
key: _formKey,
child: AutofillGroup(
child: Column(
children: [
TextFormField(
controller: _email,
keyboardType: TextInputType.emailAddress,
textInputAction: TextInputAction.next,
textCapitalization: TextCapitalization.none,
autocorrect: false,
autofillHints: const [AutofillHints.email],
decoration: const InputDecoration(labelText: 'Email'),
validator: _required,
),
const SizedBox(height: 12),
TextFormField(
controller: _password,
obscureText: _hidePassword,
textInputAction: TextInputAction.done,
autocorrect: false,
enableSuggestions: false,
autofillHints: const [AutofillHints.password],
onFieldSubmitted: (_) => _submit(),
decoration: InputDecoration(
labelText: 'Password',
suffixIcon: IconButton(
tooltip: _hidePassword ? 'Show password' : 'Hide password',
icon: Icon(
_hidePassword ? Icons.visibility : Icons.visibility_off,
),
onPressed: () =>
setState(() => _hidePassword = !_hidePassword),
),
),
validator: _required,
),
const SizedBox(height: 16),
ElevatedButton(onPressed: _submit, child: const Text('Sign in')),
],
),
),
);
}
}Pressing the action key on the email field moves focus to the password field. Pressing it on the password field calls _submit, the same path the button uses.
Common mistakes
- Treating
keyboardTypeas validation. It only changes the layout. Pasted text and hardware keyboards bypass it. - Forgetting
AutofillGroup. Without it, the OS may not link the email and password fields, and saving credentials can fail. - Using
doneon every field. The user then has to tap each next field by hand. - Reusing
AutofillHints.passwordon sign-up. UsenewPasswordso managers generate a new password. - Logging the controller text of an obscured field. Masking is visual only.
- Setting
obscureTexton a multiline field. This triggers an assertion in debug mode.
Exercise
A phone-number field uses keyboardType: TextInputType.phone and textInputAction: TextInputAction.next. A tester pastes "abc" into it on a desktop build and the form accepts the value. Why did this happen, and what should you add?
Show answer
keyboardType only selects the on-screen keyboard layout, and desktop builds with a hardware keyboard ignore it. Pasting also bypasses the layout entirely. Add a validator that rejects values that are not phone numbers, and optionally an input formatter such as FilteringTextInputFormatter to block unwanted characters as the user types.
Exercise
Which two properties would you set on a "new password" field so that the keyboard does not alter the text and the password manager suggests a strong password? Also name the widget that groups it with the username field.
Show answer
Set autocorrect: false (with enableSuggestions: false) so the keyboard leaves the text alone, and autofillHints: const [AutofillHints.newPassword] so the password manager suggests a new password. Wrap the username and password fields in an AutofillGroup.