Sub topic 3
Styling a Field with InputDecoration
This chapter assumes you can build a basic TextField, attach a TextEditingController, and write a StatefulWidget that calls setState. It also assumes you know Dart's nullable types and named parameters. By the end you will be able to describe a field's appearance with InputDecoration, control each border state, and move shared styling into the app theme.
What InputDecoration does
A TextField has no label, border or icon of its own. All of that comes from its decoration parameter, which takes an InputDecoration. Flutter hands that object to a widget called InputDecorator, which draws the label, border, icons and helper text around the editable text and animates between states.
Two points help avoid confusion later:
InputDecorationis a plain description object. It holds no state, so you can build it inline, share it, or derive a variant withcopyWith.- Passing
decoration: nullremoves the decoration entirely. The field then shows only bare text and a cursor. This is different fromconst InputDecoration(), which keeps the default Material underline.
Text around the input
Four properties place text around the field. Choose between them by when each should be visible.
| Property | Where it appears | When it is visible |
|---|---|---|
| `labelText` | Inside the field, floating above the text once focused or filled | Always |
| `hintText` | Inside the field, where the text will go | Only while the field is empty |
| `helperText` | Below the field | Until an error replaces it |
| `errorText` | Below the field, in the error color | While it is non-null |
When a field has a labelText, the hint stays hidden until the label floats up, which happens on focus. If you want the hint visible at all times, set floatingLabelBehavior: FloatingLabelBehavior.always.
Helper text and error text share one line below the field. When errorText is non-null, it replaces helperText. Because the line's height is reserved only while some text is shown, the layout can jump when an error appears. Setting helperText: ' ' (a single space) reserves the line permanently. Use it when a form should not shift as the user types.
Long error messages are cut to one line by default. Set errorMaxLines if your messages can wrap.
Icons and affixes
You can put widgets and short strings on either side of the input:
prefixIconandsuffixIconare always shown and are sized to a square touch target.prefixandsuffixare plain widgets that appear only when the field is focused or not empty. Their text counterparts areprefixTextandsuffixText, which suit units such as$orkg.iconsits outside the border, to the left of the whole field.
A suffixIcon can be interactive, and the usual example is a show/hide toggle on a password field. The icon button needs state, so the field lives in a StatefulWidget.
import 'package:flutter/material.dart';
void main() => runApp(
const MaterialApp(
home: Scaffold(
body: Padding(
padding: EdgeInsets.all(16),
child: PasswordField(),
),
),
),
);
class PasswordField extends StatefulWidget {
const PasswordField({super.key});
@override
State<PasswordField> createState() => _PasswordFieldState();
}
class _PasswordFieldState extends State<PasswordField> {
bool _obscure = true;
@override
Widget build(BuildContext context) {
return TextField(
obscureText: _obscure,
decoration: InputDecoration(
labelText: 'Password',
hintText: 'At least 8 characters',
helperText: 'Use letters and digits',
prefixIcon: const Icon(Icons.lock_outline),
suffixIcon: IconButton(
tooltip: _obscure ? 'Show password' : 'Hide password',
icon: Icon(_obscure ? Icons.visibility : Icons.visibility_off),
onPressed: () => setState(() => _obscure = !_obscure),
),
border: const OutlineInputBorder(),
),
);
}
}The tooltip on the IconButton is more than a nicety. Screen readers use it as the button's name, so an icon-only control still has a spoken label.
Borders and states
A field is always in one of several visual states, and each state can have its own border:
enabledBorderis used when the field is enabled but not focused.focusedBorderis used while the field has focus.errorBorderandfocusedErrorBorderare used when the field shows an error.disabledBorderis used when the field is disabled.borderis the fallback for any state that has no specific border.
The two common border classes are UnderlineInputBorder, the Material default, and OutlineInputBorder, a full box with optional rounded corners. Each takes a borderSide for color and width.
Set only border when you want one shape and are happy with Flutter's default color changes. Set the specific borders when the design calls for a distinct color or width per state.
Fill, density and padding
filled: truepaints a background behind the field, andfillColorchooses its color. Filled fields are the Material 3 style for text inputs.isDense: truereduces the field's vertical size. Use it in tight layouts such as toolbars and table rows.contentPaddingsets the space between the border and the text. If you shrink it too far, the floating label can collide with the input text.counterText: ''hides the character counter thatmaxLengthadds. UsebuildCounteron theTextFielditself if you want a custom counter.
Moving styling into the theme
Repeating a long InputDecoration on every field invites inconsistency. Put the shared look in ThemeData.inputDecorationTheme. Each field then supplies only what is specific to it, such as its label.
import 'package:flutter/material.dart';
ThemeData buildTheme() {
const radius = BorderRadius.all(Radius.circular(12));
return ThemeData(
useMaterial3: true,
inputDecorationTheme: InputDecorationTheme(
filled: true,
isDense: true,
contentPadding:
const EdgeInsets.symmetric(horizontal: 16, vertical: 14),
border: const OutlineInputBorder(borderRadius: radius),
enabledBorder: OutlineInputBorder(
borderRadius: radius,
borderSide: BorderSide(color: Colors.grey.shade400),
),
focusedBorder: const OutlineInputBorder(
borderRadius: radius,
borderSide: BorderSide(color: Colors.indigo, width: 2),
),
errorBorder: const OutlineInputBorder(
borderRadius: radius,
borderSide: BorderSide(color: Colors.red),
),
focusedErrorBorder: const OutlineInputBorder(
borderRadius: radius,
borderSide: BorderSide(color: Colors.red, width: 2),
),
),
);
}
void main() => runApp(
MaterialApp(
theme: buildTheme(),
home: const Scaffold(
body: Padding(
padding: EdgeInsets.all(16),
child: TextField(
decoration: InputDecoration(
labelText: 'Email',
prefixIcon: Icon(Icons.email_outlined),
),
),
),
),
),
);The field's own InputDecoration is merged over the theme, so any property you set on the field wins. Newer Flutter releases are moving theme data classes toward names ending in ThemeData, so if your SDK reports that InputDecorationTheme is the wrong type here, switch to InputDecorationThemeData.
Decoration and validation
Inside a Form, a TextFormField takes the same decoration parameter. It replaces the decoration's errorText with the error from its own validator, so an errorText you set directly is overwritten. Show errors through the validator instead of setting errorText by hand. The one case for setting errorText yourself is a plain TextField outside a form, where you compute the message in build from your own state.
Common mistakes
- Putting the decoration in the wrong place.
decorationbelongs to the field, not to a surroundingContainer. Wrapping aTextFieldin a decoratedContainerleaves the field's own underline in place. - Placing a
TextFieldin an unbounded-width parent. A field inside aRowwith noExpandedthrows a layout error, becauseInputDecoratorneeds a finite width. Wrap it inExpandedor aSizedBox. - Using
suffixwhen you want a permanent icon.suffixdisappears when the field is empty and unfocused. UsesuffixIcon. - Layout jumps from error text. Reserve the line with
helperText: ' 'if the shift bothers you. - Low-contrast hint text. Hints are not a substitute for labels, since they vanish as soon as the user types. Keep a
labelTexton every field.
Exercise
A signup form uses a TextFormField with helperText: 'We never share your email' and a validator that returns 'Enter a valid email address' for bad input. What does the user see below the field when the validator fails, and what happens to the helper text when the user corrects the input?
Show answer
While the validator returns an error, the error message 'Enter a valid email address' replaces the helper text on the same line below the field, and the border switches to the error border. Once the input is valid, the validator returns null, the error clears, and the helper text 'We never share your email' reappears.
Exercise
You want every text field in your app to have a 12-pixel rounded outline, a grey border normally, and a thicker indigo border when focused, without repeating this on each field. Where do you put the configuration, and which properties do you set?
Show answer
Put it in ThemeData.inputDecorationTheme. Set border (or enabledBorder) to an OutlineInputBorder with a 12-pixel borderRadius and a grey borderSide, and set focusedBorder to an OutlineInputBorder with the same radius and a wider indigo borderSide. Add errorBorder and focusedErrorBorder so error states match the same shape.