Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

dart

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

like image 950
StarCrossed Avatar asked Mar 25 '21 11:03

StarCrossed


1 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);
}
like image 187
Patrick O'Hara Avatar answered Sep 20 '22 16:09

Patrick O'Hara