Guide to show animation when items are entered and exit in a list using AnimatedList widget in Flutter.

The problem

List view in general is very essential in any front end framework. It contains the list of data called items to be displayed to the user. There is a high chance that item in a list may be added, removed, and changed. Now the problem is whenever any item added or removed in between the list while the user is interacting with it, This sudden change sometimes can create confusion to the user.

The solution

The simple solution is to provide a visual experience of items being added or removed by animating it. πŸ‘

So how do we do that in Flutter?

🎀 Presenting the AnimatedList Widget

An AnimatedListis a List that animates the item when inserted or removed.

Let’s try to build something like this.

Animated Widget Code looks like this

AnimatedList(
  itemBuilder: (context, index, animation) {
    return slideIt(context, index, animation);
  },
)

Properties:

β—‰ itemBuilder: This is the required parameter and is used to build items in a list. You can simply return a widget of your choice to build any item and they will be only built when they are scrolled into the view. Since we are dealing with animation, we get an animation object that will be used by the item to animate.

β—‰ controller: This is used to control the scroll position of the list.

β—‰ key: This is required in case we need to access the AnimatedList from outside and not from within the item itself.

β—‰ initialItemCount: It is used to load initial items when the list is loaded. These initial items won’t be animated. It defaults to 0.

β—‰ scrollDirection: It decides the scrolling behaviors of items.

// Items can be scrolled only bottom to top and vica versa.
scrollDirection: Axis.vertical,// Items can be scrolled only left to right and vica versa.
scrollDirection: Axis.horizontal,

β—‰ reverse: This is used to decide whether the list will be scrolled in the reading direction. It defaults to false. In the App by default, the reading direction is left-to-right so the list will be scrolled left to right. If we set this flag to true, the list will scroll in a right-to-left direction (opposite).

β—‰ primary: In iOS when we click on the status bar the list will scroll to top. It defaults to true when the scroll direction is vertical and the controller is null.

β—‰ physics: It decides how the scroll should behave on user input.

β—‰ shrinkWrap: It is used to decide whether the size (extent) of the list should take full available space or match it to the size of items in the list.

β—‰ padding: This simply adds padding around the items on the list.

Let’s make it work step by step

Step ➊**: Prepare variables**

/// Will used to access the Animated list 
final GlobalKey<AnimatedListState> listKey = GlobalKey<AnimatedListState>();/// This holds the items
List<int> _items = [];/// This holds the item count
int counter = 0;

Step βž‹**: Deploy the AnimatedList.**

AnimatedList(
  key: listKey,
  initialItemCount: _items.length,
  itemBuilder: (context, index, animation) {
    return slideIt(context, index, animation); // Refer step 3
  },
)

Step ➌**: Write a widget to display as Items in a list.**

Widget slideIt(BuildContext context, int index, animation) {
  int item = _items[index];
  TextStyle textStyle = Theme.of(context).textTheme.headline4;
  return SlideTransition(
    position: Tween<Offset>(
      begin: const Offset(-1, 0),
      end: Offset(0, 0),
    ).animate(animation),
    child: SizedBox( // Actual widget to display
      height: 128.0,
      child: Card(
        color: Colors.primaries[item % Colors.primaries.length],
        child: Center(
          child: Text('Item $item', style: textStyle),
        ),
      ),
    ),
  );
}

Note: ✍

The main item widget i.e SizedBox is wrapped inside SlideTransition. SlideTransition needs the object of Animation and we are getting the object of Animation so we use .animate method to convert it.

Step ➍**: Insert the Item.**

listKey.currentState.insertItem(0,
    duration: const Duration(milliseconds: 500));
_items = []
  ..add(counter++)
  ..addAll(_items);

For this example, we are adding any new item to the first index.

Step ➎**: Remove the Item.**

listKey.currentState.removeItem(
    0, (_, animation) => slideIt(context, 0, animation),
    duration: const Duration(milliseconds: 500));
_items.removeAt(0);

Also removing it from the first index only.

Note: ✍

  1. Whenever we insert the item in the animated list we should also update the actual list.
  2. While removing the item in step 5 we also have to pass the same widget which is used to create items because when AnimatedList removes the item, Its index is no longer available but still, it needs the UI of that item to animate like this (_, animation) => slideIt(context, 0, animation).

Here is the full code πŸ‘‡

#flutter #mobile-apps

How To Animate Items In List Using AnimatedList In Flutter
11.60 GEEK