AnimatedList and SliverAnimatedList in Flutter: How to solve problem of repeated items during bulk operations

803 views Asked by At

I am using SliverAnimatedList in my app to display a list of items.

I also implemented a several filters. If I click on Button A, certain items in the list should show up while others get removed. Same thing for Button B, C, and D. I am using a for loop to add items to and remove items from the SliverAnimatedListState.

For example:

Original list: [ 1, 2, 3 .... 20,000]
Button A filters list down to [1, 2, 3, 4]
Button B filters list down to [9, 10, 1, 5]

Filtering is done as follows:

  1. Remove all entities from original list by iterating over each present element and running removal Animation
  2. Add its members also one at a time, with a stagger animation, using a Future delay.

Clicking on the button again will remove all items and re-add the original list.

Because I am using a for loop, it is possible that a user can click Button A, and then click Button B or unclick Button A and back before all of the add/remove operations are finished, which causes duplicate items to emerge. For example:

Button A is pressed.
List is cleared. 1, 2 are added to the list.
Button B is pressed. 
1 and 2 are cleared from the list.
9 and 10 are added to the list from List B.
3 and 4 are added to the list from List A because the initial for loop did not finish running.

How would I approach solving this problem? Naturally, if I use a SliverList or a regular List without animation, I avoid the use of the for loop and then everything works as expected, but I would like to keep the animation, and am wondering is someone has an example of how to handle bulk operations in AnimatedList or SliverAnimatedList.

1

There are 1 answers

0
Randal Schwartz On

Make your source-of-truth items a map keyed on something that you require to be unique. You'll also need a way to map the index for the build to one of the Map keys as well. Perhaps a second-level map.