2

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
  • 2
    There's nothing wrong with using the null assertion operator in cases like that where you know the value isn't null. Commented Mar 4, 2021 at 14:27

1 Answer 1

2

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; } 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.