Filter ListView() items not updating

Viewed 35

I have been attempting to follow this guide for filtering ListView items. I had a few issues originally because I am pulling my list using a StreamBuilder pulling data from Firestore.

I have my filter function like this:

  // This function is called whenever the text field changes
  void _runFilter(String enteredKeyword) {
    print(enteredKeyword);
    List<GearItem> results = [];
    if (enteredKeyword.isEmpty) {
      // if the search field is empty or only contains white-space, we'll display all users
      results = _listViewItems;
    } else {
      results = _listViewItems
          .where((item) => item.itemName
              .toLowerCase()
              .contains(enteredKeyword.toLowerCase()))
          .toList();
      // we use the toLowerCase() method to make it case-insensitive
    }

    // Refresh the UI
    setState(() {
      _foundItems = results;
    });
  }

When I type in my TextField() the keyword is making it to the function but the list is not updating in the ListView.

StreamBuilder:

    //builds widget for loading and compleation
    builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
      _listViewItems.clear();
      _foundItems.clear();
      //widget build for complated call
      if (snapshot.hasData) {
        for (var i = 0; i < snapshot.data!.docs.length; i++) {
          DocumentSnapshot doc = snapshot.data!.docs[i];
          GearItem tempItem = GearItem(
            doc['itemName'],
            doc['itemTemperatureRating'],
            doc['itemType'],
            doc['itemVolume'],
            doc['itemWeight'],
            doc['itemWeightFormat'],
            doc['manufacturer'],
            doc['packCategory'],
            doc.reference.id,
            doc['itemTempFormat'],
            doc['itemVolumeFormat'],
            doc['link'],
          );
          _listViewItems.add(tempItem);
        }

        _foundItems = _listViewItems;
        ...

ListView:

        return ListView.builder(
            itemCount: _foundItems.length,
            itemBuilder: (context, index) {

Update:

After further investigation I found out my issue but am a bit stuck on how to fix it. For some reason everytime I type in my textField it not only calls the _runFilter function but also runs through the if (snapshot.hasData) and is overwriting the _foundItems list.

So the _runFilter works but then it gets overwritten each time... Any direction on which way to go from here?

So looks like set state is rebuilding everything which recalls the stream builder... I feel so close yet so far away.

0 Answers
Related