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(oldValue, newValue) {
  String value =
      newValue.text.replaceAll(RegExp(_expression(hashtag: hashtag)), '');
  late String formatted;

  for (int i = 0; i < mask.length; i++) {
    int count = mask[i].split('').where((element) => element == '#').length;
    if (count >= value.length) {
      maskPosition = i;
      break;
    }
  }
  formatted = mask[maskPosition];

  if (oldValue.text.length > newValue.text.length) {
    formatted = newValue.text;
  }
  for (var i = 0; i < value.length; i++) {
    formatted = formatted.replaceFirst('#', value[i]);
  }

  final lastHash = formatted.indexOf('#');

  if (lastHash != -1) {
    formatted = formatted.split('').getRange(0, lastHash).join();
    if (RegExp(r'\W$').hasMatch(formatted)) {
      formatted = formatted.substring(0, formatted.length - 1);
    }
  }

  return TextEditingValue(
    text: formatted,
    selection: TextSelection.collapsed(offset: formatted.length),
  );
}