4

I'm trying to find a way to add a blank space while typing in a TextFormField.

I found a way how to do this a while back but I cannot find it now, no matter what I search for on Google or here on StackOverflow ..

Basically I want to turn the text shown in the textfield from 000011112222333 to 0000 1111 2222 3333

I'm guessing I need to use some RegExp check in the onChanged function of a TextFormField and use it to change the TextEditingController's .text

0

4 Answers 4

15

I also faced this problem before and luckily found a way to do this somewhere. First create a class that extends TextInputFormatter

customInputFormatter.dart

class CustomInputFormatter extends TextInputFormatter {
  @override
  TextEditingValue formatEditUpdate(TextEditingValue oldValue, TextEditingValue newValue) {
    var text = newValue.text;

    if (newValue.selection.baseOffset == 0) {
      return newValue;
    }

    var buffer = new StringBuffer();
    for (int i = 0; i < text.length; i++) {
      buffer.write(text[i]);
      var nonZeroIndex = i + 1;
      if (nonZeroIndex % 4 == 0 && nonZeroIndex != text.length) {
        buffer.write(' '); // Replace this with anything you want to put after each 4 numbers
      }
    }

    var string = buffer.toString();
    return newValue.copyWith(
        text: string,
        selection: new TextSelection.collapsed(offset: string.length)
    );
  }
}

And then add it to the list of inputFormatters[] of TextFormField

inputFormatters: [
   FilteringTextInputFormatter.digitsOnly,
   new CustomInputFormatter()
],   
11
  • Nice one! Will check this out tomorrow but this looks similar to what I found before so sure it will work :D
    – Chris
    Oct 29, 2020 at 17:35
  • 1
    Hi mate, I gave this a go but it's formatting the string like this "4444 4 4 4 4 4" .. I also can't seem to create the FilteringTextInputFormatter.digitsOnly ... is that necessary?
    – Chris
    Oct 30, 2020 at 9:16
  • Can you post the code of how you implemented it? The FilteringTextInputFormatter.digitsOnly is to ensure that you can only enter number (digits). This is because I think you want to implement this for credit card
    – Dung Ngo
    Oct 30, 2020 at 9:24
  • I created a class using the exact code you have above and added a parameter for my custom TextFormField widget that takes a List<TextInputFormatter> ... Then I've simply added the CustomInputFormatter in the way you have above
    – Chris
    Oct 30, 2020 at 9:39
  • 1
    Cursor is jumping and adding unnecessary spaces when i used this solution
    – lordvidex
    Oct 23, 2021 at 19:07
4

Inspired from Dung Ngo's Code

I added cursor tracking so when the user erases from the the TextFormField the cursor doesn't goes back to the beginning of field.

I commented the WhitelistingTextInputFormatter.digitsOnly / FilteringTextInputFormatter.digitsOnly in my pen since I used regular expressions.

Here's the pen https://codepen.io/brocatz/pen/dyNOqVy

@override
TextEditingValue formatEditUpdate(TextEditingValue oldValue, TextEditingValue newValue) {
    var text = newValue.text;
    text = text.replaceAll(RegExp(r'(\s)|(\D)'), '');

    int offset = newValue.selection.start;
    var subText =
        newValue.text.substring(0, offset).replaceAll(RegExp(r'(\s)|(\D)'), '');
    int realTrimOffset = subText.length;

    // if (newValue.selection.baseOffset == 0) {
    //   return newValue;
    // }

    var buffer = new StringBuffer();
    for (int i = 0; i < text.length; i++) {
      buffer.write(text[i]);
      var nonZeroIndex = i + 1;
      if (nonZeroIndex % 4 == 0 && nonZeroIndex != text.length) {
        buffer.write(
            ' '); // Replace this with anything you want to put after each 4 numbers
      }


      if (nonZeroIndex % 4 == 0 &&
          subText.length == nonZeroIndex &&
          nonZeroIndex > 4) {
        int moveCursorToRigth = nonZeroIndex ~/ 4 - 1;
        realTrimOffset += moveCursorToRigth;
      }

      if (nonZeroIndex % 4 != 0 && subText.length == nonZeroIndex) {
        int moveCursorToRigth = nonZeroIndex ~/ 4;
        realTrimOffset += moveCursorToRigth;
      }
    }

    var string = buffer.toString();
    return newValue.copyWith(
        text: string,
        selection: new TextSelection.collapsed(offset: realTrimOffset));
  }
1
  • unfortunately this solution gives the following error: W/TextInputPlugin(10676): Changing the content within the the composing region may cause the input method to behave strangely, and is therefore discouraged. See github.com/flutter/flutter/issues/78827 for more details which results in Strange behavior. For Example if you switch from Alphabetic to numeric Keyboard, after each Space the Keyboard switches back. Anyone does have a solution for this? Jul 1, 2021 at 11:19
0
  1. Declare the following class.
class CustomInputFormatter extends TextInputFormatter {
  final int? inputLength;
  //inputLength = 16 -> if input == 'XXXX XXXX XXXX XXXX'(16 characters)
  //inputLength = 12 -> if input == 'XXXX XXXX XXXX'(12 characters)
  //inputLength is optional.

  CustomInputFormatter({this.inputLength});

  @override
  TextEditingValue formatEditUpdate(
      TextEditingValue oldValue, TextEditingValue newValue) {
    String left = oldValue.text.substring(0, min(oldValue.selection.start, newValue.selection.end));
    String right = oldValue.text.substring(oldValue.selection.end);
    String inserted = newValue.text.substring(left.length, newValue.selection.end);
    String modLeft = left.replaceAll(" ", "");
    String modRight = right.replaceAll(" ", "");
    String modInserted = inserted.replaceAll(" ", "");
    if (inputLength != null) {
      modInserted = modInserted.substring(0,
          min(inputLength! - modLeft.length - modRight.length,
              modInserted.length));
    }
    final regEx = RegExp(r'\d{1,4}');
    String updated = regEx
        .allMatches((modLeft + modInserted + modRight).toUpperCase())
        .map((e) => e.group(0))
        .join(" ");
    int cursorPosition = regEx
        .allMatches(modLeft + modInserted)
        .map((e) => e.group(0))
        .join(" ").length;
    return TextEditingValue(
        text: updated,
        selection: TextSelection.collapsed(
            offset: cursorPosition));
  }
}
  1. Then in the TextFormField:
TextFormField(
    inputFormatters: [
    FilteringTextInputFormatter.allow(RegExp(r'\d|\s')),
    CustomInputFormatter(inputLength: 16),
  ];
 )

(make sure to add CustomInputFormatter() at the end.)

-2

in flutter 2.2 you should use FilteringTextInputFormatter.allow(RegExp(r'[0-9]')) instead of FilteringTextInputFormatter.digitsOnly

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.