numberFormatters static method

List<TextInputFormatter> numberFormatters({
  1. required int decimal,
  2. required bool allowNegative,
  3. required double? max,
})

Implementation

static List<TextInputFormatter> numberFormatters(
    {required int decimal,
    required bool allowNegative,
    required double? max}) {
  final RegExp regex =
      RegExp('[0-9${decimal > 0 ? '.' : ''}${allowNegative ? '-' : ''}]');
  return [
    TextInputFormatter.withFunction((oldValue, newValue) {
      if (newValue.text == '') {
        return newValue;
      }
      if (allowNegative && newValue.text == '-') {
        return newValue;
      }
      final double? parsed = double.tryParse(newValue.text);
      if (parsed == null) {
        return oldValue;
      }
      final int indexOfPoint = newValue.text.indexOf('.');
      if (indexOfPoint != -1) {
        final int decimalNum = newValue.text.length - (indexOfPoint + 1);
        if (decimalNum > decimal) {
          return oldValue;
        }
      }

      final double? oldParsed = double.tryParse(oldValue.text);

      if (max != null && parsed > max) {
        if (oldParsed != null && oldParsed > parsed) {
          return newValue;
        }
        return oldValue;
      }
      return newValue;
    }),
    FilteringTextInputFormatter.allow(regex)
  ];
}