I recently got into flutter and dart and I've been writing basic programs. Just this morning I ran into an error when trying to convert user input from a string into an integer so I could perform a mathematical operation. Here's the code.
import "dart:io";
import "dart:math";
import "dart:convert";
void main() {
print("Enter a number: ");
String num1 = stdin.readLineSync();
print("Enter a second number");
String num2 = stdin.readLineSync();
print(int.parse(num1) + int.parse(num2));
}
Surprisingly this runs well on the online dart compiler and interpreter. (replit)
but when I run it on vscode
, I get this error
"Error: A value of type 'String?' can't be assigned to a variable of type 'String' because 'String?' is nullable and 'String' isn't.
String num2 = stdin.readLineSync();"
Whichever data type I use, I get the same error. be it var
, or string
, or int
or double
.
I tried another method of conversion but its the same thing. works on the online compiler, doesn't work on my machine. here's the code.
import "dart:io";
import "dart:math";
import "dart:convert";
void main() {
print("Enter a number: ");
var num1 = stdin.readLineSync();
var num2 = int.parse(num1);
print("Enter a second number");
var num3 = stdin.readLineSync();
var num4 = int.parse(num3);
print(num2 + num4);
}