'String?' can not convert to 'String' in dart

Viewed 2134

A value of type 'String?' can't be assigned to a variable of type 'String'. Try changing the type of the variable, or casting the right-hand type to 'String'. This error message i got when i run this code.

This is a simple user input code on dart.

    var person = ['abc', 'qwe', 'dfg'];
    stdout.write('Enter Index : ');
    String p = stdin.readLineSync(); //Error
    int per = int.parse(p);

    per > person.length
      ? stderr.write('Index does not exist')
      : stdout.write('Person ${person[per]}');
    }
2 Answers

Seems like readLineSync() returns nullable type. But you declare variable p as non-nullable. Either declare p as nullable: String? instead of String or make readLineSync() return default value if null:

String p = stdin.readLineSync() ?? "";// will return empty String if method readLineSync() returns null.

First of all check the null safety documentation, you'll learn everything you need to know https://dart.dev/null-safety/understanding-null-safety

readLineSync returns a value of Type String? Meaning the return value must be a nullable String.

p is of type String and therefore expects a String (not a nullable String). the trick here is to cast stdin.readLineSync() to String:

String p = stdin.readLineSync() as String;
String p = stdin.readLineSync()!; #shorthand syntax

On top of that, your code needs some improvements. What if p can't be cast into an integer? One way to handle this is to add a try block and catch any FormatException.

Related