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,
) {
assert(
min == null ||
max == null ||
!stepStrictly ||
(min! % step == 0 && max! % step == 0),
'当严格步进时,min 和 max 都应是 step 的整数倍',
);
String text = newValue.text;
final num? value = num.tryParse(text);
if (value == null) {
return const TextEditingValue();
}
if (min != null && value < min!) {
return oldValue;
}
if (max != null && value > max!) {
return oldValue;
}
if (stepStrictly && value % step != 0) {
text = ((value ~/ step) * step).toString();
}
if (precision != null && text.contains('.')) {
final list = text.split('.');
final int decimalLength = list.last.length;
final int integerLength = list.first.length;
if (decimalLength > precision!) {
text = text.substring(0, integerLength + 1 + precision!);
}
}
return TextEditingValue(
text: text,
selection: newValue.selection.copyWith(
baseOffset: math.min(newValue.selection.start, text.length),
extentOffset: math.min(newValue.selection.end, text.length),
),
composing: !newValue.composing.isCollapsed &&
text.length > newValue.composing.start
? TextRange(
start: newValue.composing.start,
end: math.min(newValue.composing.end, text.length),
)
: TextRange.empty,
);
}