Home > Mobile >  conditional filtering in array and sum
conditional filtering in array and sum

Time:05-24

In the code below I am getting three drinks based on age 13. I want to filter that list based on age, if the age is less than 15, it should only display drinks that can not contain alcohol and also how to calculate the sum of the item based on the same condition using for loop.

Thanks! You can run this code on the dartPad

class Drink {
final int id;
final String? name;
final int? price;
final bool isAlchol;

Drink(this.id, this.name, this.price, this.isAlchol);
}

void main() {
final List<Drink> beverage = [
Drink(1, 'cola', 2, false),
Drink(2, 'fanta', 3, false),
Drink(3, 'coctail', 5, true),
Drink(4, 'beer', 5, true),
];

 final userAge = 15;
 final userSelectedDrinkList = [1, 2, 3];
 final paidCash = 20;

  void getNewDrink(List<int> itemList, int age, int cash) {
  final userDrinks =
    beverage.where((drink) => itemList.contains(drink.id)).toList();
  for (final drink in userDrinks) {
  print(drink.name);
  }
  }

  getNewDrink(userSelectedDrinkList, userAge, paidCash);
  }

CodePudding user response:

Here are a few functions that will help you.

To filter a list and remove the drinks with alcohol :

List<Drink> getDrinksWithoutAlcohol(List<Drink> initialList) {
  return initialList.where((drink) => !drink.isAlchol).toList();
}

To get the total price of a list of beverages in a for loop

int getTotalPrice(List<Drink> listDrinks) {
  int price = 0;
  for(Drink drink in listDrinks) {
    price  = drink.price ?? 0;
  }

  return price;
}

And based on the code you provided, if you want to conditionally filter your list depending on the user's age, you could do the following

final finalList = userAge < 15 ? getDrinksWithoutAlcohol(userDrinks) : userDrinks;

CodePudding user response:

You could just tweak your code a bit.. something like this:

  void getNewDrink(List<int> itemList, int age, int cash) {

    final userDrinks = beverage
      .where((drink) => itemList.contains(drink.id))
      .where((drink) => age >= 15 || !drink.isAlchol)
      .toList();
    
    final sum = userDrinks.map((drink) => drink.price).reduce((value, element) => (value ?? 0)   (element ?? 0));
    
    print(sum);
    
    for (final drink in userDrinks) {
      print(drink.name);
    }
  }

or you could obviously do the summation with the for-loop:

var anotherSum = 0;
for (final drink in userDrinks) {
  anotherSum  = drink.price ?? 0;
}
  • Related