0

I have a textfield, and i save the value to a variable called message message is a nullable field String? message; as usual, because it can be null before user enters text right?.. however when checking if it's empty, I've done this

if(message != null && message != '') {
  // use the message for a super secret super suspicious act
}

but this isn't enough for me coz when user types one space, and sends it, it accepts it as not empty, I tried to tackle this by adding the condition && message != ' ' this worked, but now, user can type two spaces and send, I added another condition for two spaces, till I started feeling stupid, I can't handle all the spaces, so I tried using an .isNotEmpty property, but it wouldn't let me, because as you know, message is nullable, and you can't use .isNotEmpty on a field that has the potential of being null, only work around is to add a null check to message which I can't do coz I know at some point message is gonna be null, it'll definitely throw an exception,

SO the big question is, is there a way to make sure user can't send empty messages, or work around my condition by sending a bunch of spaces, how do chat apps like whatsapp and the likes of it make sure you can't send spaces and pass it as a string

  • 2
    Create a copy of the string, use a RegExp to remove all spaces and check the remaining string's length. If it is 0, it only contained spaces. After the `message != null` check you can safely use `message!` which will work where non nullable values are not allowed. – Peter Koltai May 10 '22 at 14:32
  • thanks a lottt, worked, you could add it as an answer so i can mark it as the answer – public static void Main May 10 '22 at 16:48
  • 1
    use ?? to add default variable null, example: message ?? ''. https://stackoverflow.com/questions/54031804/what-are-the-double-question-marks-in-dart – anggadaz May 11 '22 at 03:20

1 Answers1

0

Try using .trim()

String message = "       ";
message.trim();
print(message);
devIbraz
  • 11
  • 1