Search code examples
fluttertextformfield

Flutter - How to add space after 1 character when typing in TextFormField


I tried this solution from the other question: How to: add a blank space after every 4 characters when typing in TextFormField and changed only the 4 to 1. But this solution has some issues like here mention: How to: add a blank space after every 4 characters when typing in TextFormField

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

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

    var buffer = StringBuffer();
    for (int i = 0; i < text.length; i++) {
      buffer.write(text[i]);
      var nonZeroIndex = i + 1;
      if (nonZeroIndex % 1 == 0 && nonZeroIndex != text.length) {
        buffer.write(' ');
      }
    }

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

Solution

  • You can replace all spaces and add spaces in a loop. Also the last space isn't added so you can delete the values

    class CustomInputFormatter extends TextInputFormatter {
      @override
      TextEditingValue formatEditUpdate(TextEditingValue oldValue, TextEditingValue newValue) {
        var text = newValue.text;
    print(text);
        if (newValue.selection.baseOffset == 0) {
          return newValue;
        }
    
        var buffer = StringBuffer();
        text = text.replaceAll(" ", "");
        for (int i = 0; i < text.length; i++) {
          buffer.write(text[i]);
         if(i < (text.length-1))buffer.write(" ");
        }
    
        var string = buffer.toString();
        return newValue.copyWith(
            text: string,
            selection: TextSelection.collapsed(offset: string.length)
        );
      }
    }