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

Total
0
Shares

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);
^


Solution

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);
}

Source: StackOverflow.com

Leave a Reply

Your email address will not be published. Required fields are marked *