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); ^
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With