Dart Null Safety / Assertion Operator

Viewed 113

I'm new to Dart. I'm calculating the price of a pizza order. In my current solution, I'm using the assertion operator. What do you think about it?

I've read many times that you shouldn't use it. Do you think my code is ok, or would you do something better/different?

void main() {
  const List<String> order = ['margherita', 'pepperoni', 'pineapple'];
  calcTotalPrice(order: order);
}

calcTotalPrice({required List<String> order}) {
  final Map<String, double> pizzaPrices = {
    'margherita': 5.5,
    'pepperoni': 7.5,
    'vegetarian': 6.5
  };

  double total = 0.0;

  for (var item in order) {
    pizzaPrices[item] ??= 0.0;
    total += pizzaPrices[item]!; // assertion operator (!)
  }

  print(total);
}
1 Answers

Your code is fine but you can avoid collecting unknown keys in the map pizzaPrices with:

for (var item in order) {
  total += pizzaPrices[item] ?? 0.0;
}
Related