Understand itemBuilder: in AnimatedList (Flutter)

Viewed 123

I want to add an animated list to my Flutter application I've been looking at a bunch of tutorials and they all use this syntax to crate an item builder function - enter image description here

The code is working but I still don't understand a few things.

  1. From where the animation and index came I did not declared them nor initialized them with any value ?
  2. What increments the index ?
  3. What makes the code iterate over the entire list ?

Maybe I'm just being a rookie not understating Dart or Flutter well enough but I would really apricate some help clarifying this subject.

1 Answers

itemBuilder is a property defined as follow in the constructor of AnimatedList:

final AnimatedListItemBuilder itemBuilder;

And AnimatedListItemBuilder is a type defined like this:

typedef AnimatedListItemBuilder =
  Widget Function(BuildContext context, int index, Animation<double> animation);

So basically itemBuilder is a method which could be compared to a build method in a widget. Its purpose is to define how a defined number of items will be build.

Now to answer your three questions:

  1. animation and index are internal variables defined inside SliverAnimatedListState. It is a State of SliverAnimatedList which is the widget used to render AnimatedList under the hood. As you might already expect index is the index of the item to build and animation is the animation applied to the widget.

  2. The index increments itself automatically based on the parameter initialItemCount. Basically there is an internal variable which will decrement itself until it reaches 0 to build the correct number of items.

  3. I think I've already answered to this question with 2). It iterates for each decrementation of itemCount until it reaches 0 and will call itemBuilder to render the widget.

Related