phoneNumberFormatter static method

List<TextInputFormatter> phoneNumberFormatter()

phoneNumberFormatter formats input as a phone number (e.g., (XXX) XXX-XXXX).

Implementation

static List<TextInputFormatter> phoneNumberFormatter() {
  return [
    TextInputFormatter.withFunction((oldValue, newValue) {
      String newText = newValue.text.replaceAll(RegExp(r'\D'), '');
      if (newText.length > 10) {
        newText = newText.substring(0, 10);
      }
      final StringBuffer buffer = StringBuffer();
      int selectionIndex = newValue.selection.end;

      if (newText.isNotEmpty) {
        buffer.write('(');
        if (selectionIndex >= 1) selectionIndex++;
      }
      for (int i = 0; i < newText.length; i++) {
        if (i == 3) {
          buffer.write(') ');
          if (selectionIndex >= 3) selectionIndex += 2;
        } else if (i == 6) {
          buffer.write('-');
          if (selectionIndex >= 6) selectionIndex++;
        }
        buffer.write(newText[i]);
      }

      final String formattedText = buffer.toString();
      return TextEditingValue(
        text: formattedText,
        selection: TextSelection.collapsed(offset: selectionIndex),
      );
    }),
  ];
}