Home > Net >  apply multiple conditional filters on a ListView
apply multiple conditional filters on a ListView

Time:03-03

I'm a new flutter developer and would like to use multiple filters on my List. I'm using a ListView :


ListView.builder(
itemBuilder: (ctx, index) =>
MealCard(_customList[index]),
itemCount: _customList.length,
                          ),

and my Meal class have the following properties:

 Meal {
final String id,
final String title, 
final String imgUrl, 
final bool isLowCalorie,
final bool isVegan,
final bool isBreakfat, 
final bool isDinner,
final bool isLunch}

I'd like to apply different filters based on the booleans included within my class; I have some methods that look something like this:

 List<Meal> get breakfastFilter {
    return _meals.where((element) => element.isBreakfast).toList();
  }

  List<Meal> get lunchFilter {
    return _meals.where((element) => element.isLunch).toList();
  }

  List<Meal> get dinnerFilter {
    return _meals.where((element) => element.isDinner).toList();

However these methods allow me to create a single list, what if I wish to add additional filters together and create a combination of two lists.

CodePudding user response:

You can do it something like this:

 bool filterItem(element){
    return element.isVegan&&element.isBreakfat;
  }
    
  _meals.where((element) => filterItem(element)).toList();  

CodePudding user response:

There's many ways to do it but you can try to use boooleans combined with optional parameters like this:

getMealFilter(_meals,
    {bool lookForBreakfast = false,
    bool lookForVegan = false,
    bool lookForLunch = false}) {
  return _meals
      .where((element) =>
          (lookForBreakfast && element.isBreakfast) ||
          (lookForVegan && element.isBreakfast) ||
          (lookForLunch && element.isLunch))
      .toList();
}

I just put 3 filters, but you can easily add the rest. How this works is that if, for example, lookForBreakfast is false, element.isBreakfast is ignored. (false and something is always false), and so on for the others parameters.

  • Related