mishalhaneef
mishalhaneef

Reputation: 862

How to add two values from list in dart

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

Upvotes: 1

Views: 1482

Answers (5)

Kerby Elpenord
Kerby Elpenord

Reputation: 205

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

Upvotes: 0

bhagavati antala
bhagavati antala

Reputation: 185

  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());

Upvotes: 2

Manishyadav
Manishyadav

Reputation: 1746

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

Upvotes: 1

bhagavati antala
bhagavati antala

Reputation: 185

  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());
  

Upvotes: 0

mmcdon20
mmcdon20

Reputation: 6746

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'];

Upvotes: 4

Related Questions