Home > Software engineering >  How to properly filter a List with Dart/Flutter
How to properly filter a List with Dart/Flutter

Time:01-31

I'm struggling to find a way to properly filter a list with dart/flutter without losing its content.

For context:

  • I have a list with 100 items.
  • I use this list in a ListView
  • I have a button to filter the list using the Where().ToList()
  • Once filtered, the original list get reduced to the filtered value and I can't recover the initial (100 values)

My understand (or lack of) is that even if I create a new object copying the list, still references the original, so the original gets deleted. So I am not sure how can I use filters without losing data?

The filter call:

 onTap: (int index) {
        switch (index) {
          case 0:
            widget.collection!.items =
                widget.collection!.filterCollection(FilterType.all);
            _selectedIndex = index;
            break;
          case 1:
            widget.collection!.items =
                widget.collection!.filterCollection(FilterType.onlyFew);
            _selectedIndex = index;
            break;
        }

On the filterCollection (which is a method inside the class that hold the items) I added a secondary list (filteredList where I tried to keep the original list so I could revert back to it, but doesnt work either)

filterCollection(FilterType filter) {
    filteredList.clear();
    filteredList.addAll(items); //items is a List<Items> part of this class
    switch (filter) {
      case FilterType.onlyFew:
        return filteredList
            .where((element) => element.something == true)
            .toList();
      case FilterType.all:
      default:
        return filteredList;
    }

My latest guess (which I will try now) is to try to use a "copy" of the list in the widget.collection so I don't change the original? I don't know, completely lost :D

Any suggestion?

CodePudding user response:

You should have a list with all items and a second list with the filtered items.

Default the filteredList should have the initial list with all items. Your ListView only works with the filteredList.

Inside your onTap set your filteredList:

switch (index) {
          case 0:
            filteredList =
                widget.collection!.filterCollection(FilterType.all);
            _selectedIndex = index;
            break;
          case 1:
            filteredList =
                widget.collection!.filterCollection(FilterType.onlyFew);
            _selectedIndex = index;
            break;
        }
  • Related