Error: The argument type 'String?' can't be assigned to the parameter type 'String' because 'String?' is nullable and 'String' isn't

Viewed 53685

Good day, I have been trying the below code:

import 'dart:io';
main (){
print ("write your birth year:");
var birthyear = stdin.readLineSync();
var birthyearint = int.parse(birthyear);
var age = 2021-birthyearint;
print(age);
}

when I run it I receive the following error:

5:30: Error: The argument type 'String?' can't be assigned to the parameter type 'String' because 'String?' is nullable and 'String' isn't. var birthyearint = int.parse(birthyear); ^

2 Answers

The error is caused by the null safety feature in Dart, see https://dart.dev/null-safety.

The result of method stdin.readLineSync() is String?, i.e. it may be a String, or it may be null. The method int.parse() requires a (non-null) String. You should check that the user gave some input, then you can assert that the value is non-null using birthyear!. Better still, you should use int.tryParse() to check that the user input is a valid integer, for example:

var birthyearint = int.tryParse(birthyear ?? "");
if (birthyearint == null) {
    print("bad year");
} else {
    var age = 2021-birthyearint;
    print(age);
}

enter image description hereSolution for this error ; just add : var birthyear = stdin.readLineSync(); to read from keyboard; also This error is caused by the null safety feature in Dart: i tried this and successfully passed. This link may help you : https://dart.dev/guides/libraries/library-tour .. . . . .

Related