'MasonryGridView Flutter dynamically search/filter items

I am using the MasonryGridView from the flutter_staggered_grid_view package and trying to implement a search function that shows only the items that match the search query with their title. It works, but there is this weird bug that sometimes one item duplicates in the view but in reality, it is another item that has its image now.

I have a setState for the query and every time it gets called the search function triggers.

  void searchForItems(String text) {
    if (text == "") {
      setState(() {
        widget.currentItems = widget.items;
      });
    } else {
      List<Item> filteredItems = [];
      for (final Item element in widget.items) {
        if (element.getText().toLowerCase().contains(text.toLowerCase())) {
          filteredItems.add(element);
        }
      }
      final filteredItemsSet = {...filteredItems};
      setState(() {
        widget.currentItems = filteredItems;
      });
    }
  }


  @override
  Widget build(BuildContext context) {
    searchForItems(widget.searchInput);
    return BlocBuilder<StorageCubit, StorageState>(
      builder: (context, state) {
          return staggeredGridView();
      },
    );
  }

  Widget staggeredGridView() => MasonryGridView.count(
        crossAxisCount: 2,
        itemCount: widget.currentItems.length,
        mainAxisSpacing: 4.0,
        crossAxisSpacing: 4.0,
        itemBuilder: (BuildContext context, int index) {
          final item = widget.currentItems[index];

          final itemImage = BlocProvider.of<StorageCubit>(context).getImage(
            widget.items[index],
            ImageType.small,
            atIndex: 0,
            isTemp: false,
          );

          itemImage.then((value) {
            final imageFileId = item.imageFileIds.firstOrNull;
            if (imageFileId != null) imageCache[imageFileId] = value;
            return value;
          });

          return InkResponse(
            splashColor: HexColors.collectoBlue,
            onTap: () => _openItem(widget.currentItems[index]),
            child: ItemCell(
              item: item,
              image: itemImage,
              cachedImage: item.imageFileIds.firstOrNull != null
                  ? imageCache[item.imageFileIds.first]
                  : null,
            ),
          );
        },
      );


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source