Sub topic 5
Restricting and shaping input with formatters
This chapter assumes you can build a TextField or TextFormField with a controller and a validator, and that you know how keyboardType is set. It covers inputFormatters, which change the text while the user types, before any validator sees it.
What a formatter does
An input formatter is an object that receives every edit to a field. It gets the previous value and the proposed new value, and it returns the value the field will actually hold. It can accept the edit, modify it, or reject it by returning the old value.
Flutter's formatters all extend TextInputFormatter. You attach them with the inputFormatters list on TextField or TextFormField.
A TextEditingValue holds three things: the text, the selection (cursor position or highlighted range), and the composing range used by input methods such as those for Japanese or Chinese. A formatter that changes text without fixing selection makes the cursor jump, so keep this in mind for the custom formatters later in the chapter.
Formatters run in list order, and each one receives the output of the one before it. Because of this, order matters. A length limit placed before a formatter that inserts spaces counts different characters than the same limit placed after it.
Built-in formatters
| Formatter | Effect | Typical use |
|---|---|---|
| `FilteringTextInputFormatter.digitsOnly` | Keeps only the characters 0 to 9 | ZIP codes, PINs |
| `FilteringTextInputFormatter.allow(RegExp)` | Keeps only the parts of the text that match | Decimal amounts |
| `FilteringTextInputFormatter.deny(Pattern)` | Removes the parts of the text that match | Blocking spaces or symbols |
| `LengthLimitingTextInputFormatter(n)` | Truncates the text to `n` characters | Fixed-length codes |
The following example combines the built-in formatters in a small form with a ZIP code field and a price field.
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
void main() => runApp(const MaterialApp(home: Scaffold(body: Demo())));
class Demo extends StatelessWidget {
const Demo({super.key});
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.all(16),
child: Column(
children: [
TextFormField(
keyboardType: TextInputType.number,
inputFormatters: [
FilteringTextInputFormatter.digitsOnly,
LengthLimitingTextInputFormatter(5),
],
decoration: const InputDecoration(
labelText: 'ZIP code',
hintText: '12345',
),
),
TextFormField(
keyboardType:
const TextInputType.numberWithOptions(decimal: true),
inputFormatters: [
FilteringTextInputFormatter.allow(RegExp(r'^\d*\.?\d{0,2}')),
],
decoration: const InputDecoration(
labelText: 'Price',
prefixText: '\$ ',
),
),
],
),
);
}
}The import 'package:flutter/services.dart'; line is required. The formatter classes live there, not in material.dart.
How `allow` and `deny` work
allow does not test the whole string against the pattern. It finds every match of the pattern in the text and joins the matches together. The price pattern ^\d*\.?\d{0,2} matches at most once, from the start of the string. If the user pastes 12.345, the match is 12.34, and the field keeps that. If the user pastes abc, the match is empty and the field becomes empty.
digitsOnly is stricter than many people expect. It rejects the decimal point, the minus sign, and spaces. For a price or a signed number, use allow with a regular expression, as above.
Length limits and `maxLength`
TextField also has a maxLength parameter. It installs a length limit, and it shows a counter below the field, such as 3/5. Use maxLength when you want the counter. Use LengthLimitingTextInputFormatter when you want the limit without the counter. You can also hide the counter by setting counterText: '' in the InputDecoration.
The limit counts characters as the user sees them (grapheme clusters), not UTF-16 code units. A single emoji counts as one character, even though Dart's String.length reports more than one for it.
What formatters do not do
Three limits are worth knowing before you rely on formatters.
keyboardTypedoes not restrict input. It only picks which keyboard appears. A user can still paste letters into a number field, and a hardware keyboard can type anything. Add a formatter if the field must contain only digits.- Formatters do not run on programmatic changes. Setting
controller.text = 'abc'bypassesinputFormatters. Formatters see only edits made through the text input system. If you pre-fill a field from saved data, clean the data yourself. - Formatters do not replace validators. A formatter can leave a field in a state that is valid to type but invalid to submit. A ZIP code limited to five digits can still contain two digits. The validator checks completeness, and the formatter only prevents bad characters.
Writing a custom formatter
When the built-in classes are not enough, extend TextInputFormatter and override formatEditUpdate. The example below formats a card number as groups of four digits, such as 1234 5678 9012 3456, and keeps the cursor in the right place when the user edits in the middle of the number.
import 'package:flutter/services.dart';
class CardNumberFormatter extends TextInputFormatter {
static const _maxDigits = 16;
@override
TextEditingValue formatEditUpdate(
TextEditingValue oldValue,
TextEditingValue newValue,
) {
final raw = newValue.text;
var digits = raw.replaceAll(RegExp(r'\D'), '');
if (digits.length > _maxDigits) {
digits = digits.substring(0, _maxDigits);
}
final buffer = StringBuffer();
for (var i = 0; i < digits.length; i++) {
if (i > 0 && i % 4 == 0) buffer.write(' ');
buffer.write(digits[i]);
}
final text = buffer.toString();
// Count the digits that were before the cursor in the unformatted
// text, then find where that many digits sit in the formatted text.
final cursor = newValue.selection.end;
var offset = text.length;
if (cursor >= 0) {
final before = raw.substring(0, cursor.clamp(0, raw.length));
final digitsBefore =
before.replaceAll(RegExp(r'\D'), '').length.clamp(0, digits.length);
offset = digitsBefore + (digitsBefore > 0 ? (digitsBefore - 1) ~/ 4 : 0);
}
return TextEditingValue(
text: text,
selection: TextSelection.collapsed(offset: offset),
);
}
}Use it with inputFormatters: [CardNumberFormatter()] and keyboardType: TextInputType.number. Do not add digitsOnly before it, because that would remove the spaces the formatter inserts on the next edit. The custom formatter already discards non-digits.
Three details in this code are the common sources of bugs:
newValue.selectioncan be invalid, with offsets of-1, when the field has no cursor yet. The code falls back to the end of the text.- The cursor position is computed from digits, not from characters. Spaces are added and removed by the formatter, so character offsets in the old text no longer match the new text.
- The formatter returns a value with no
composingrange. That is acceptable for digits. For text that uses an input method, dropping the composing range can interrupt composition, so do not apply this pattern to such fields.
One-off formatters
For a small transformation, TextInputFormatter.withFunction avoids a new class.
final upperCase = TextInputFormatter.withFunction(
(oldValue, newValue) => newValue.copyWith(text: newValue.text.toUpperCase()),
);This is safe for most Latin text. Some characters change length when uppercased, for example the German ß becomes SS. In that case the old selection can point past the end of the new text, so a field that must accept such characters needs the cursor handling shown above.
Reading formatted values
The controller holds the formatted text, and the validator receives the formatted text too. A card validator therefore checks for 19 characters, including three spaces. Before sending the value anywhere, strip the formatting.
String? validateCard(String? value) {
final digits = (value ?? '').replaceAll(' ', '');
if (digits.isEmpty) return 'Card number is required';
if (digits.length != 16) return 'Enter all 16 digits';
return null;
}
String cardDigits(String formatted) => formatted.replaceAll(' ', '');Keeping the display format and the stored format separate avoids a class of bugs where 1234 5678 is sent to a payment API that expects digits.
Testing a formatter
A formatter is a plain object, so you can test it without building any widgets.
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
test('groups digits and moves the cursor past the new space', () {
final formatter = CardNumberFormatter();
final result = formatter.formatEditUpdate(
TextEditingValue.empty,
const TextEditingValue(
text: '12345',
selection: TextSelection.collapsed(offset: 5),
),
);
expect(result.text, '1234 5');
expect(result.selection.baseOffset, 6);
});
test('ignores letters and extra digits', () {
final result = CardNumberFormatter().formatEditUpdate(
TextEditingValue.empty,
const TextEditingValue(
text: 'a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6q7',
selection: TextSelection.collapsed(offset: 34),
),
);
expect(result.text, '1234 5678 9012 3456');
});
});This file needs CardNumberFormatter imported from wherever you defined it, using the package path of your own project.
Exercise
A ZIP field uses keyboardType: TextInputType.number and no inputFormatters. A user pastes "12a45" into it. What does the field contain, and what is the smallest change that makes it hold "1245"?
Show answer
The field contains "12a45", because keyboardType only chooses the keyboard and does not filter pasted text. Add inputFormatters: [FilteringTextInputFormatter.digitsOnly] to the field. The paste is then filtered to "1245".
Exercise
You set controller.text = '1234567890123456' in initState for a field that uses CardNumberFormatter. What does the field show, and how do you fix it?
Show answer
It shows "1234567890123456" with no spaces, because formatters only run on edits made through the text input system, not on programmatic assignment. Fix it by formatting the value yourself before assigning it, for example by calling the formatter's formatEditUpdate with TextEditingValue.empty and the new value, and using the returned text.