mddg
mddg

Reputation: 695

Custom TextInputFormatter

I'm developing a Flutter side project. I've been coding with Fltuter and Dart for quite a bit and I'm trying to make things look more professional.
The thing is that I have a register form in which the user is asked for their phone number. My intention is to make the output look like: ### ### #### - for example: 123 456 7890 - while the user is typing.
I've been trying to figure out how does TextInputFormatter work yet I can't get the expected results.

Could you please give an example on how to do it?

Cheers

EDIT (Added code snippet):
If tried adding the first space with this (I've been trying to follow this tutorial).

class PhoneInputFormatter extends TextInputFormatter {
  @override
  TextEditingValue formatEditUpdate(
    TextEditingValue oldValue,
    TextEditingValue newValue,
  ) {
    final String text = newValue.text;
    final int textLength = text.length;
    int selectionIndex = newValue.selection.end;
    int usedSubstringIndex = 0;
    final StringBuffer buffer = StringBuffer();

    if (textLength < 4) {
      buffer.write(text.substring(0, textLength));
    }

    // ### ### ####
    if (textLength >= 4) {
      buffer.write(text.substring(0, usedSubstringIndex = 2));
      buffer.write(' ');
      buffer.write(text[3]);

      selectionIndex++;
    }

    return newValue.copyWith(
      text: buffer.toString(),
      selection: TextSelection.collapsed(offset: selectionIndex),
    );
  }
}

An image of the form

Upvotes: 2

Views: 3787

Answers (1)

Omatt
Omatt

Reputation: 10473

You can follow this answer posted on this question which seems similar to your use case. Just omit this portion to not add a + at the start of the field.

// Remove this part
if (newTextLength >= 1) {
  newText.write('+');
  if (newValue.selection.end >= 1) selectionIndex++;
}

Upvotes: 1

Related Questions