formatEditUpdate method

  1. @override
TextEditingValue formatEditUpdate(
  1. TextEditingValue oldValue,
  2. 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) {
  int selectionIndex;

  // Get the previous and current input strings
  String pText = oldValue.text;
  String cText = newValue.text;
  // Abbreviate lengths
  int cLen = cText.length;
  int pLen = pText.length;

  if (cLen == 1) {
    // Can only be 0, 1, 2
    if (int.parse(cText) > 2) {
      // Remove char
      cText = '0$cText:';
    }
  } else if (cLen == 2 && pLen == 1) {
    // Hours cannot be greater than 24
    int dd = int.parse(cText.substring(0, 2));
    if (dd == 0 || dd > 23) {
      // Remove char
      cText = cText.substring(0, 1);
    } else {
      // Add a / char
      cText += ':';
    }
  } else if (cLen == 4) {
    String minutesDecimals = cText.split(':')[1];

    if (int.parse(minutesDecimals) > 5) {
      // Remove char
      cText = cText.substring(0, 3);
    }
  } else if (cLen > 5) {
    cText = cText.substring(0, 5);
  }

  selectionIndex = cText.length;
  return TextEditingValue(
    text: cText,
    selection: TextSelection.collapsed(offset: selectionIndex),
  );
}