Removing Items

Now that we’ve covered how to add an item, it is time to wire our function to remove them.

An important thing to note about removing an item in AnimatedList is the item is immediately removed from the list however it will remain visible on screen for the duration of time specified. Once removed, its index will no longer be passed to AnimatedList.builder .

Before we can actually remove an item, let’s clean up our current code. We will start by changing the way our item is built. Instead of building it directly, let’s create a new function _buildItem() . This function will be responsible for building our ListTile .

Notice our function has two parameters one of which is optional. The reason for this will become clear as we continue. Also take note of the ValueKey around our ListTile . Since our widgets are cached by Flutter, we need a way to uniquely identify them.

At this point, running our code will cause a crash. This is because ValueKey uses the == operator to compare widgets. Since we are using a custom type, we need to override the == operator and hashCode for our UserModel . If you are using InteliJ, you can use Alt+Ins in UserModel and select "generate == and hashCode". Select all three fields and hit “ok”.

Now with our refactoring complete, let’s move on to our delete function. From the code we refactored you may have noticed that we changed our onLongPressed to use a function deleteUser . Let us now create this function.

The above snippet shows the function for removing an item from this list. Fist, the index of the item we want to remove is passed to the function as a parameter. Next, we remove it from our listData . At this point, the item is removed however it is still visible on screen because we did not remove it from our AnimatedList . To do this, we use _listKey.currentState.removeItem() .

The method removeItem has three parameters, index , builder and an optional parameter duration . When this method is called, it starts a reversed animation that is passed to builder . This allows us to animate the item off-screen. For this example, we are going to both a FadeTransition and SizeTransition .