1

This is a list of pizza prices

  const pizzaPrices = {
    'margherita': 5.5,
    'pepperoni': 7.5,
    'vegetarian': 6.5,
  };

how to calculate the total for a given order. if margherita and pepperoni then it should be 13$.

const order = ['margherita', 'pepperoni'];

how do i add to list

5 Answers 5

4

There are a few approaches you can calculate the total. One way would be to use fold:

final total =
    order.fold<double>(0.0, (prev, elem) => prev + pizzaPrices[elem]!);

Another way would be to loop through the order and add up the total imperatively:

var total = 0.0;
for (final elem in order) {
  total += pizzaPrices[elem]!;
}

In order to add to your list, you would call the add method on the list:

order.add('vegetarian');

However, a const list cannot be modified, so you would have to change order to be declared as either final or var:

final order = ['margherita', 'pepperoni'];
Sign up to request clarification or add additional context in comments.

Comments

2
  const pizzaPrices = {
    'margherita': 5.5,
    'pepperoni': 7.5,
    'vegetarian': 6.5,
  };
  const order = ['margherita', 'pepperoni'];
  var total=0.0;
  order.forEach((item){
    total+=pizzaPrices[item]??0.0;  
  });
  print("Total : "+total.toString());

Comments

1

So if you use this than you don't have to define your own ```fold`` function.

var sum = [1, 2, 3].reduce((a, b) => a + b);

You can visit this for more clearity, https://github.com/dart-lang/sdk/issues/1649

Or

num sum = 0;
for (num e in [1,2,3]) {
  sum += e;
}

Comments

0
  const pizzaPrices = {
    'margherita': 5.5,
    'pepperoni': 7.5,
    'vegetarian': 6.5,
  };
  const order = ['margherita', 'pepperoni'];
  
  var total=0.0;
  order.forEach((item){
     pizzaPrices.forEach((name,price){
       if(name==item){
         total=total+price;
       }
     });
  });
  
  print("Total : "+total.toString());
  

2 Comments

This does not make efficient use of the map. Instead of looping over every map entry using foreach just subscript [] into the pizzaPrices map using the item variable.
yes you are right please check my second answer
0
void main() {
  const pizzaPrices = {
    'margherita': 5.5,
    'pepperoni': 7.5,
    'vegetarian': 6.5,
  };

  var x = pizzaPrices['margherita'];
  var y = pizzaPrices['pepperoni'];

  List xy = [];

  xy.add(x);
  xy.add(y);

  double somme = 0;

  xy.forEach((var element) => somme += element);

  print(somme);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.