I recently started dart programing, I encountered a issue while doing it, I was doing it by referring this website https://hackmd.io/@kuzmapetrovich/S1x90jWGP
Error: A value of type 'String?' can't be assigned to a variable of type 'num'.
My code :
import 'dart:io';
void main() {
print('Enter a number');
var num1 = stdin.readLineSync();
var num2= 100-num1;
}
can anyone tell whats the issue and how to fix.
CodePudding user response:
you can parse String into
int
var num2 = 100 - int.parse(num1!);
or double
var num2 = 100 - double.parse(num1!);
CodePudding user response:
So stdin.readLineSync()
reads your console input and will store it to num1
of type var
. As you can see in the documentation, stdin.readLineSync()
returns a String?
.
Because the data type of var
variables is resolved during runtime, num1
will be of type String?
after assigning the console input to it.
So the problem of your code is, that you try to subtract 100 from a string, which is not possible.
To solve this issue you should better convert your input into a numerical type, like int
or double
. But be careful! Your input could also contain character that can't be converted to a number. One solution could look like following:
void main() {
print('Enter a number');
var input = stdin.readLineSync();
var num1 = double.parse(input);
if (num1 != null){
var num2 = 100 - num1;
}else{
// num1 could not be converted to a double
// handle exception here
}
}
For the beginning, I recommend you to use data types in your code instead of var
and val
. Maybe reading something about dart's type system may also be helpful.