31

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

StarCrossed
  • 341
  • 1
  • 3
  • 10

2 Answers2

27

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);
}
Patrick O'Hara
  • 1,999
  • 1
  • 14
  • 18
1

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 .. . . . .

Sa_IS
  • 33
  • 4
  • Please see [Why should I not upload images of code/data/errors when asking a question?](https://meta.stackoverflow.com/questions/285551/why-should-i-not-upload-images-of-code-data-errors-when-asking-a-question) (it applies to answers too) – ggorlen Jul 15 '22 at 02:51