Home > Enterprise >  Flutter: filter a List<Map<String, dynamic>> to only contain certain items
Flutter: filter a List<Map<String, dynamic>> to only contain certain items

Time:02-02

I have a list of maps where one of the fields in the map is a boolean called "completed". I want to be able to filter the map so that I only get the items for which "completed" is true or false. My current code is the following:

   try {
      String? email = FirebaseAuth.instance.currentUser!.email;
      for (int i = startingIndex; i < endingIndex;   i) {
        var doc = await FirebaseFirestore.instance
            .collection(email!)
            .doc("goals")
            .collection(Utils.goalsCategoriesDropdownItems[i])
            .get();
        if (doc.size > 0) {
          allData.addAll(doc.docs.map((doc) => doc.data()).toList());
        }
      }
      allData.sort(((a, b) {
        Timestamp one = a["dueDate"];
        Timestamp two = b["dueDate"];
        return one.compareTo(two);
      }));
      return allData;
    }

but I don't want to return allData, I want to filter and see if all the items are true or false, so I want something like this:

      if (completed == true) {
        allData.map((e) => e["completed"] == true);
      } else {
        allData.map((e) => e["completed"] == false);
      }
      return allData;

CodePudding user response:

It is not entirely clear what your expected outcome is, but here are two possibilities:

a) If you want to check if every Map in your List has the key completed with a value of true you can use every:

return allData.every((e) => e["completed"] === true)

b) If you want to have a list containing only Maps which contain the key completed with a value of true you can use where:

return allData.where((e) => e["completed"] === true)
  • Related