Home > Software design >  How to add two values from list in dart
How to add two values from list in dart

Time:12-18

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

CodePudding user response:

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

CodePudding user response:

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

CodePudding user response:

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

CodePudding user response:

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

CodePudding user response:

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

}

have an nice day

  • Related