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) {
String? last;
if (newValue.text.length > oldValue.text.length &&
(last = lastCharacter(newValue)) != null &&
newlinePattern.contains(last!)) {
// Trim from right side and then split newline, get the latest line.
final selectionStart = newValue.selection.start;
final prevLine = _getPreviousLine(newValue.text, selectionStart - 1);
final length = prevLine.runes.takeWhile(isSpace).length;
final indent = "".padLeft(length);
// If line includes any header catch it.
String? header = bulletListHeader(prevLine, length);
String before = newValue.selection.textBefore(newValue.text);
int removedLength = 0;
// If header is present but is null, remove header
if (header == null) {
header = '';
final prev = lineTrimmed(prevLine, length);
if (isEmptyHeader(prev)) {
removedLength = prev.length + 1;
before =
'${before.substring(0, before.length - removedLength - 1)}\n\n';
}
}
final value = [
before,
indent,
header,
newValue.selection.textInside(newValue.text),
newValue.selection.textAfter(newValue.text)
].join();
return newValue.copyWith(
text: value,
selection: TextSelection.collapsed(
offset: newValue.selection.baseOffset +
length +
header.length -
removedLength,
),
);
}
return newValue;
}