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

Time:08-15

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
}

CodePudding user response:

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.

  • Related