graywartz doomski
graywartz doomski

Reputation: 43

How do I tell flutter that just inputting SPACE should be considered null in my flutter texting app?

I'm creating a basic texting app on flutter. At the moment just hitting the spacebar n times and hitting send would result in a text bubble with n spaces. How do I tell flutter that just spaces should be considered null or should not be sent?

Upvotes: 0

Views: 3342

Answers (2)

Christopher Moore
Christopher Moore

Reputation: 17113

In general, you should trim the String that you're going to send with the trim method. Trimming removes whitespace that usually isn't needed, just like in this case. Input formatters are not necessary and may prevent users from typing. Wherever you're getting your text input and sending it, add in this trimming.

String toSendString = inputText.trim(); //Send toSendString instead of inputText

You may only want to trim a certain side of the String instead, which can be done with trimLeft or trimRight.

Then, if the string is empty toSendString.isEmpty, don't send the message.


Alternatively, if trimming every message is for some reason undesirable, you can just check if all of the characters are spaces and conditionally send the message based on that with something like the following:

bool isAllSpaces(String input) {
  String output = input.replaceAll(' ', '');
  return output == '';
}

Upvotes: 6

Krish Bhanushali
Krish Bhanushali

Reputation: 2007

First of all you need to provide what are you using for the input. So if you are using Textfield for input you can use Regex Expression in the input so now one cannot start a sentence with a space this is a work around but will stop user to enter blank spaces all the way and should impose at least one letter required.

 TextField(
                                  inputFormatters: [
                                    
                                  WhitelistingTextInputFormatter(RegExp(r'[^-\s][a-zA-Z0-9-_\\s]+$')),
                               ] ),

Add the inputFormatters property in your textfield. There also may be better solution than this but this will definitely restrict user to not send all blank message

Upvotes: 0

Related Questions