Home > Mobile >  The argument type 'double?' can't be assigned to the parameter type 'num',
The argument type 'double?' can't be assigned to the parameter type 'num',

Time:05-28

I have this function:

double discount() {
    return cost_min_discounted != null ? cost_min - cost_min_discounted : 0;
}

cost_min_discounted is defined as double?
I get the error:

The argument type 'double?' can't be assigned to the parameter type 'num'

What's the best way to write code like that? I check for the null value, so the code seems correct to me.

CodePudding user response:

While you've already checking null at beginning, use ! at the end.

double discount() {
  return cost_min_discounted != null ? cost_min - cost_min_discounted! : 0;
}

CodePudding user response:

The above function will execute well! If you are tring to assign cost_min_discounted to any num value like:

num n = cost_min_discounted;

This will give error.

Instead try to check null condition here:

num n = cost_min_discounted==null ? 0: cost_min_discounted!;
  • Related