formatEditUpdate method
Called when text is being typed or cut/copy/pasted in the EditableText.
You can override the resulting text based on the previous text value and the incoming new text value.
When formatters are chained, oldValue
reflects the initial value of
TextEditingValue at the beginning of the chain.
Implementation
@override
TextEditingValue formatEditUpdate(
TextEditingValue oldValue, TextEditingValue newValue) {
final text =
newValue.text.replaceAll(' ', ''); // Remove any existing spaces
if (text.length <= 4) {
return newValue.copyWith(
text: text); // If the text is 4 characters or less, return as is
}
// Split the text into groups of 4 characters
final formattedText = StringBuffer();
for (int i = 0; i < text.length; i++) {
if (i > 0 && i % 4 == 0) {
formattedText.write(' '); // Add a space every 4 characters
}
formattedText.write(text[i]);
}
return newValue.copyWith(
text: formattedText.toString(),
selection: TextSelection.collapsed(offset: formattedText.length),
);
}