Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can a string user input somehow be a non string or null type?

I am asking for a user input, and it has to be a String and not null afterall.

Can somehow an user enter a non string value or null? so I would be force to validate it?
or I can safely skip this validation code? (since it is redundat)

String? userInput = stdin.readLineSync();

if (userInput != null){
  if (userInput.runtimeType == String){
    print('Validated input');
  } else{ // if is not a string
    print('You did not entered a string');
  }
  print('You entered a null value'); // if null
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

First, you should, in general, not use .runtimeType in production code. E.g. in your example it would be better to use if (userInput is String) to test if userInput are compatible with the String type. The difference is that we often don’t care about exact types but rather if something is just compatible with a given type.

Next, the stdin.readLineSync() is defined to return String? which means it is enforced by the type system to return a String or null. It can’t return e.g. a number.

So your if (userInput != null) is actually enough since if this is the case, we know for a fact that userInput must then be a String.

import 'dart:io';

void main() {
  String? userInput = stdin.readLineSync();

  if (userInput != null){
    print('Validated input. Input must be a String.');
  } else {
    print('You entered a null value by closing the input stream!');
  }
}

For when userInput can become null, it happens if the user are closing stdin input stream. You can do that in bash (and in other terminals) by using Ctrl+D keyboard shortcut. If doing so, the userInput would become null.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading