formatEditUpdate method Null safety
- TextEditingValue oldValue,
- TextEditingValue newValue
override
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 newValueLength = newValue.text.length;
var selectionIndex = newValue.selection.end;
var substrIndex = 0;
final newText = StringBuffer();
if (newValueLength > maxLength) {
return oldValue;
}
switch (newValueLength) {
case 1:
final hora = int.parse(newValue.text.substring(0, 1));
if (hora >= 3) return oldValue;
break;
case 2:
final hora = int.parse(newValue.text.substring(0, 2));
if (hora >= 24) return oldValue;
break;
case 3:
final minuto = int.parse(newValue.text.substring(2, 3));
if (minuto >= 6) return oldValue;
newText.write(newValue.text.substring(0, substrIndex = 2) + ':');
if (newValue.selection.end >= 2) selectionIndex++;
break;
case 4:
final minuto = int.parse(newValue.text.substring(2, 4));
if (minuto >= 60) return oldValue;
newText.write(newValue.text.substring(0, substrIndex = 2) + ':');
if (newValue.selection.end >= 2) selectionIndex++;
break;
}
if (newValueLength >= substrIndex) {
newText.write(newValue.text.substring(substrIndex));
}
return TextEditingValue(
text: newText.toString(),
selection: TextSelection.collapsed(offset: selectionIndex),
);
}