Home > Enterprise >  The function finds only one element, even if there is more than one
The function finds only one element, even if there is more than one

Time:01-04

The function below finds only one item in the list, even if there are multiple items, how do I fix this function to find all items?

List newList = [];

if (value.isNotEmpty) {
   for (var element in pressures) {
       if (element.pressure.contains(value) ||
          element.date.toString().contains(value)) {
          newList.clear();
          newList.add(element);
       }
   }
   items.value = newList;
 } else {
   items.value = pressures;
 }

CodePudding user response:

You are clearing the list on loop

if (value.isNotEmpty) {
   newList.clear(); // you can clear it on top of the loop
   for (var element in pressures) {
       if (element.pressure.contains(value) ||
          element.date.toString().contains(value)) {
         // newList.clear(); //remove this
          newList.add(element);
       }
   }
   items.value = newList;
 } else {
   items.value = pressures;
 }
  • Related