Search code examples
flutterdartdart-null-safety

The argument type 'double?' can't be assigned to the parameter type 'num', even if I check if the value is not null


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.


Solution

  • 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;
    }