format method

  1. @override
FormatResult format(
  1. TextEditingValue value,
  2. int position
)
override

Implementation

@override
FormatResult format(TextEditingValue value, int position) {
  var i = 0;
  var v = value;
  var finished = false;

  final g = grouping;

  num number = 0;

  while ((position + i) < v.text.length && !finished) {
    final char = v.text[position + i];
    final nextChar =
        v.text.length == position + i + 1 ? null : v.text[position + i + 1];
    if (g is WithGrouping && char == g.groupingSymbol) {
      if (nextChar == null || !nextChar.isDigit) {
        finished = true;
        continue;
      }
      v = v.replaced(
        TextRange(start: position + i, end: position + i + 1),
        '',
      );
      i--;
      continue;
    }
    if ('-' == char && i == 0) {
      if (!allowNegative) {
        v = v.replaced(
          TextRange(start: position + i, end: position + i + 1),
          '',
        );
      } else {
        i++;
      }
      continue;
    }
    if (char.isDigit) {
      i++;
      continue;
    }
    finished = true;
  }
  if (i == 0) {
    return FormatResult(v, 0, null);
  }
  if (i != 0) {
    final numberText = v.text.substring(position, position + i);
    number = numberText == '-' ? 0 : num.parse(numberText);
  }
  if (i != 0 && g is WithGrouping) {
    final realPartLength = i;
    for (var j = 0; j < realPartLength; j++) {
      if (j != 0 && j % g.groupSize == 0) {
        v = v.replaced(
          TextRange.collapsed(position + realPartLength - j),
          g.groupingSymbol,
        );
        i++;
      }
    }
  }
  if (i == 0) {
    v = v.replaced(TextRange.collapsed(position + i), '0');
    i++;
  }

  return FormatResult(v, i, number);
}