Flutter & Textfield : How do I restrict my user from using space in textfield by automatically removing that space?
Asked Answered
Z

5

8

How do I restrict my user from using space in textfield by automatically removing that space when the user finish typing?

For example, if the user type King of Light, it will apply as KingofLight after he/she steps away from the textfield.

TextFormField(
                          initialValue: nickname != null
                              ? nickname
                              : current_user.nickname,
                          decoration: InputDecoration(
                            border: new OutlineInputBorder(
                              borderSide: new BorderSide(color: Colors.grey),
                              borderRadius: BorderRadius.circular(6),
                            ),
                            focusedBorder: OutlineInputBorder(
                              borderSide:
                                  BorderSide(color: Colors.grey, width: 1.0),
                              borderRadius: BorderRadius.circular(6),
                            ),
                            enabledBorder: OutlineInputBorder(
                              borderSide:
                                  BorderSide(color: Colors.grey, width: 1.0),
                              borderRadius: BorderRadius.circular(6),
                            ),
                            hintText: 'Empty',
                            hintStyle: TextStyle(
                              color: Colors.grey[400],
                              fontSize: 20,
                              //fontWeight: FontWeight.bold,
                            ),
                          ),
                          style: TextStyle(
                            fontSize: 20,
                            // fontWeight: FontWeight.bold,
                          ),
                          validator: (val) => val.length < 2
                              ? 'Enter a nickname 2+char long'
                              : null,
                          onChanged: (val) {
                            val = val.replaceAll(' ', '');
                            setState(() => nickname = val);
                          },
                        ),

please help me! thank you!

Zackzackariah answered 7/10, 2020 at 7:56 Comment(1)
see TextInputFormatterRussophobe
U
5

One way you do this is like this using TextEditingController and can call formatNickname() as per your use case.

class _MyWidgetState extends State<MyWidget>{
  
  FocusNode node = new FocusNode();
  TextEditingController tc = TextEditingController();
  
  @override
  void initState(){
    node.addListener((){
      if(!node.hasFocus){
        formatNickname();
      }
    });
    super.initState();
  }
  
  void formatNickname(){
    tc.text = tc.text.replaceAll(" ", "");
  }
  
  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        TextFormField(
          focusNode: node,
          controller: tc,
        ),
        TextFormField(),
        RaisedButton(
          child: Text('Format'),
          onPressed: (){
            formatNickname();
          },
        ),
      ],
    );
  }
}
Unmoved answered 7/10, 2020 at 8:24 Comment(0)
E
30

Text field which does not allow spaces, using RegExp. As below-

            TextFormField(
               inputFormatters: [
                if (denySpaces)
                  FilteringTextInputFormatter.deny(
                      RegExp(r'\s')),
              ])

Above solution worked for me, to block space from keyboard.

Eliott answered 29/6, 2021 at 14:19 Comment(2)
Seems a robust solution against the combination of FocusNode and TextEditingControllerBellaude
What is the variable denySpaces?Horror
U
5

One way you do this is like this using TextEditingController and can call formatNickname() as per your use case.

class _MyWidgetState extends State<MyWidget>{
  
  FocusNode node = new FocusNode();
  TextEditingController tc = TextEditingController();
  
  @override
  void initState(){
    node.addListener((){
      if(!node.hasFocus){
        formatNickname();
      }
    });
    super.initState();
  }
  
  void formatNickname(){
    tc.text = tc.text.replaceAll(" ", "");
  }
  
  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        TextFormField(
          focusNode: node,
          controller: tc,
        ),
        TextFormField(),
        RaisedButton(
          child: Text('Format'),
          onPressed: (){
            formatNickname();
          },
        ),
      ],
    );
  }
}
Unmoved answered 7/10, 2020 at 8:24 Comment(0)
I
4

Another option to disable the possibility of writing spaces in a TextField, you can use an input formatter to restrict the allowed characters.

import 'package:flutter/services.dart';

class NoSpaceFormatter extends TextInputFormatter {
  @override
  TextEditingValue formatEditUpdate(
      TextEditingValue oldValue, TextEditingValue newValue) {
    // Check if the new value contains any spaces
    if (newValue.text.contains(' ')) {
      // If it does, return the old value
      return oldValue;
    }
    // Otherwise, return the new value
    return newValue;
  }
}

We created a new class called NoSpaceFormatter that extends TextInputFormatter. The formatEditUpdate() method is called whenever the user types or deletes a character in the TextField.

Inside the formatEditUpdate() method, we check if the new value contains any spaces by calling the contains() method on the text property of the newValue parameter. If it does contain spaces, we return the oldValue, which prevents the user from typing the space character. Otherwise, we return the newValue, which allows the user to type the character.

To use the NoSpaceFormatter class in a TextField, you can set the inputFormatters property to a list containing an instance of the formatter:

TextField(
  inputFormatters: [NoSpaceFormatter()],
  // Other properties...
)
Ivy answered 2/3, 2023 at 5:52 Comment(0)
N
3
    TextFormField(
       style: const TextStyle(fontSize: 30),
              inputFormatters: [
                  FilteringTextInputFormatter.deny(
                     RegExp(r'\s')),
        ],
   )
Nobody answered 29/4, 2023 at 15:20 Comment(0)
J
0

I'm success with:

TextField(
   inputFormatters: [
     FilteringTextInputFormatter.deny(RegExp(r'\s')), 
   ],
),
Judijudicable answered 26/4, 2024 at 4:26 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.