Home > front end >  Filtering arrays in Dart
Filtering arrays in Dart

Time:05-20

Can anyone guide me and tell me where I am making mistake in the code. I want to filter all the pizzas which have Pizzatype veggie. I am getting an empty array in the output.

main() {
   
    final pizzaWithToppings =
      PizzaWithToppings('Mushroom Pizza', 12, [1, 2, 3], [], PizzaType.veggie );
  
     final pizzaWithToppings2 =
      PizzaWithToppings('Chiken Pizza', 20, [1, 2, 3], [], PizzaType.meatLover);
  
    final pizzaWithToppings3 =
      PizzaWithToppings('Veggie Pizza', 15, [1, 2, 3], [], PizzaType.veggie);
  
    final pizzaList = [pizzaWithToppings, pizzaWithToppings2,pizzaWithToppings3];
  
    final findVeggiePizza = pizzaList.where((pizza) =>   pizzaList.contains(PizzaType.veggie) ).toList();
  
    print (findVeggiePizza);
}

CodePudding user response:

where iterates one pizza at a time. Something like this might work.

final findVeggiePizza = pizzaList.where((pizza) =>  pizza.type == PizzaType.veggie).toList();

CodePudding user response:

Probably as so

enum PizzaType {
  veggie,
  meatLover
}


class PizzaWithToppings {
  String typeDes;
  int price;
  List list;
  PizzaType type;

  PizzaWithToppings(this.typeDes, this.price, this.list, this.type);
  
  bool filter(PizzaType type) {
    return this.type == type;
  }
  
}


void main() {

    final pizzaWithToppings =
      PizzaWithToppings('Mushroom Pizza', 12, [1, 2, 3], PizzaType.veggie);
  
     final pizzaWithToppings2 =
      PizzaWithToppings('Chiken Pizza', 20, [1, 2, 3], PizzaType.meatLover);
  
    final pizzaWithToppings3 =
      PizzaWithToppings('Veggie Pizza', 15, [1, 2, 3], PizzaType.veggie);
  
    final pizzaList = [pizzaWithToppings, pizzaWithToppings2,pizzaWithToppings3];
        
    final findVeggiePizza = pizzaList.where((pizza) =>  pizza.filter(PizzaType.veggie)).toList();
  
    print (findVeggiePizza);
}

Is that so?

  • Related