Animate screen switches for IndexedStack in Flutter
TL;DR — It’s a simple 3 step process:
Hide (with animation) → Update Index → Show (with animation)
Long(er) Explanation
I’ll try to keep it as short and simple as possible. So there’s this very well known problem in the Flutter community about there not being an easy way to animate the screen switching process inside an IndexedStack.
Let’s take an example of the following simple code:
Preview
As a refresher to people who can’t recall why we need to use an IndexedStack instead of just an AnimatedSwitcher, the reason is that an IndexedStack keeps all its children in-memory to avoid having to rebuild any of them when the user switches between screens. This feature comes in handy when you want to, for example, preserve the state of all top-level destinations of your app (like the current scrolled position of the screen).
And NO, putting IndexedStack inside AnimatedSwitcher doesn’t work because for AnimatedSwitcher to do its magic, you’ll have to provide IndexedStack a key that gets updated whenever you change the index, but doing so would cause the IndexedStack itself to be rebuilt, hence all its children would also get rebuild thereby defeating the whole purpose of using IndexedStack in the first place, so.. this is the worst possible scenario in terms of performance 😂
Therefore while scouring the internet for a solution, I got inspired by packages and solutions like FadeIndexedStack (gist, package) that did almost the same thing, but the experience was not quite there yet, it still felt a little jittery because whenever you switched, it instantly snapped to the new screen, and then started the animation.
Therefore, I tried to tweak that code and come up with something that would satisfy my current app’s need (i.e. to provide a nice and smooth user experience).
Welcome EasyAnimatedIndexedStack
I’ve published that code as a library on pub.dev to make it easier for you to just import the dependency and consume it. Although I will do my best to keep it updated with the latest possible Flutter/Dart version, it is sometimes best to just own your code and have it inside your codebase instead of depending on a 3rd party library, that’s why I am sharing the widget’s code below as well.
Now, let’s update the sample code we saw above and just replace IndexedStack with our new EasyAnimatedIndexedStack, so the code would now look like:
You can also customise the animation to your liking by overriding the curve, duration, and animationBuilder properties:
You can find the code in its GitHub repository here. Just download the file and put it into your project if you don’t want to rely on 3rd party dependencies.
Hats off to you if you made it so far 🫡 And I hope this article and the library were useful. You can find me on X and LinkedIn for any queries.
Until next time, stay well and happy ✌🏼