I get this error every time I try to run my code:
""New.dart:5:5: Error: The value 'null' can't be assigned to the parameter type 'int' because 'int' is not nullable.
Y:null,""
Here's my code
void main()
{
print (addition(
X:1,
Y:2,
Z:3,));
}
int addition({int X, int Y, int Z}) {
return X * Y * Z;
}
As you can see I've already given them a value and they're not null, so what's the problem?
CodePudding user response:
Try adding the keyword required in front of all the int
. You are putting them as non nullable optional parameters but without specifying default values.
int addition({required int X,required int Y,required int Z}) {
return X * Y * Z;
}
CodePudding user response:
If you are going to be passing the value anyways, you can always make the parameter required.
void main()
{
print (addition(X:1,Y:2,Z:3));
}
int addition({required int X, required int Y, required int Z}) {
return X Y Z;
}
If you still want to make the parameters optional:
void main()
{
print (addition(X:1,Y:2,Z:3));
}
int addition({ int? X, int? Y, int? Z}) {
if (X!=null && Y!=null && Z!=null){
return X Y Z;
} else{
//DO this or handle it your own way.
throw Exception('One or more parameter is null.');
}
}
The reason your code is not working is that you are specifying the type as int
but dart doesn't know whether the value will be null or not. Either you can put required
in front to make it required which means you will have to pass the integer value on the function or you can use the int?
which means you are expecting the value that is being passed in the function to be null. This way, you cannot return the result unless you handle the null condition.