Search code examples
flutterdartflutter-layoutflutter-animationflutter-animatedlist

Flutter Retrigger Staggered Animation on ListView


I am using flutter_staggered_animations in my app for my listView. It is working quite nice when starting the app.

Problem:

I want the animation to be triggered if I change the child-widget of the listView or even just the itemCount. So what I need is a rebuild of the staggeredList.

But how can I do that? I tried simply changing the child or itemCount with setState. But that is triggering an animation...

Couldn't find anything on this. Let me know if you need more info!

I use pretty much the exact code from the example:

@override
Widget build(BuildContext context) {
  return Scaffold(
    body: AnimationLimiter(
      child: ListView.builder(
        itemCount: 100,
        itemBuilder: (BuildContext context, int index) {
          return AnimationConfiguration.staggeredList(
            position: index,
            duration: const Duration(milliseconds: 375),
            child: SlideAnimation(
              verticalOffset: 50.0,
              child: FadeInAnimation(
                child: YourListChild(),
              ),
            ),
          );
        },
      ),
    ),
  );
}

Solution

  • You can provide a new key on AnimationLimiter, and it will recreate the AnimationLimiter,

    AnimationLimiter(
      key: ValueKey("$itemCount"),
      child: ListView.builder(
    
    class STA extends StatefulWidget {
      const STA({super.key});
    
      @override
      State<STA> createState() => _STAState();
    }
    
    class _STAState extends State<STA> {
      int itemCount = 5;
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          floatingActionButton: FloatingActionButton(
            onPressed: () {
              itemCount++;
              setState(() {});
            },
          ),
          body: AnimationLimiter(
            key: ValueKey("$itemCount"),
            child: ListView.builder(
              itemCount: itemCount,
              itemBuilder: (BuildContext context, int index) {
                return AnimationConfiguration.staggeredList(
                  position: index,
                  duration: const Duration(milliseconds: 375),
                  child: SlideAnimation(
                    verticalOffset: 50.0,
                    child: FadeInAnimation(
                      child: Padding(
                        padding: const EdgeInsets.all(8.0),
                        child: Container(
                          height: 50,
                          color: index.isEven ? Colors.amber : Colors.purple,
                        ),
                      ),
                    ),
                  ),
                );
              },
            ),
          ),
        );
      }
    }