AnimatedBuilder: Isolate Animation Rebuilds for Performance
Flutter's AnimatedBuilder rebuilds only the widgets that change during an animation, not the entire screen. Use it to embed a moving part within a larger static widget, like a spinning icon on a button, to maximize performance.
WHY IT EXISTS In Flutter, animations can trigger 60 rebuilds per second. If an animation is part of a large, complex widget, rebuilding the entire widget 60 times is computationally expensive and can cause jank. AnimatedBuilder was created to solve this by rebuilding only a small, targeted part of the widget tree.
THE MENTAL MODEL Think of AnimatedBuilder as a surgical tool for UI updates. Instead of making your whole widget a StatefulWidget to manage an animation, you wrap just the moving part in an AnimatedBuilder. It listens for ticks from an animation and rebuilds only its small builder function, leaving the rest of your UI untouched and performant.
HOW IT WORKS You provide an AnimatedBuilder with a Listenable (like an AnimationController) and a builder function. Whenever the Listenable notifies its listeners, AnimatedBuilder calls your builder function to reconstruct just that part of the widget tree. For a major performance boost, you can define a static part of your UI once, pass it to AnimatedBuilder's child parameter, and it will be passed into your builder without being rebuilt on every frame.
WHEN TO USE IT Use AnimatedBuilder when you need to animate a widget that is part of a larger, more complex widget tree. It excels at decoupling animation logic from widget build logic, which improves both readability and performance. A spinning icon on a card or a pulsing button are perfect use cases.
WHEN NOT TO USE IT For very simple cases where the entire widget is the animation, extending AnimatedWidget can be simpler. For implicit animations where you just want to animate a property to a new value (e.g., fade in), TweenAnimationBuilder is easier as it manages its own controller. If your listenable is not an Animation (like a ChangeNotifier), use ListenableBuilder for better code clarity, though it is functionally identical.
ONE CANONICAL EXAMPLE To create a continuously spinning square without rebuilding its parent, you would use an AnimationController. You'd wrap a Transform.rotate widget inside an AnimatedBuilder that listens to the controller. The Container for the square itself, which doesn't change, would be passed as the child to the AnimatedBuilder. This ensures only the rotation is recalculated each frame, not the square's color, shape, or size.
Read the original → api.flutter.dev
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.