Flutter › Flutter Animations Basics

How does the AnimatedBuilder widget let you efficiently rebuild only the specific part of your widget tree that actually needs to change on every single animation frame, rather than rebuilding an entire larger, unrelated widget subtree unnecessarily?

Intermediate

Answer

The AnimatedBuilder widget listens to a provided Animation object and automatically calls its own builder function on every single frame update while that animation is actively running, and by passing an already constructed, unchanging child widget into AnimatedBuilder through its dedicated child parameter, Flutter can efficiently avoid rebuilding that potentially expensive child widget on every single frame, since only the specific, smaller builder function itself actually needs to run repeatedly, which is a particularly important optimization for animations involving a genuinely expensive child widget that should not need to be needlessly reconstructed many times every single second.
AnimatedBuilder(
  animation: controller,
  builder: (context, child) {
    return Transform.rotate(angle: controller.value * 6.28, child: child);
  },
  child: ExpensiveWidget(),
)
Real-world example A custom loading spinner uses AnimatedBuilder to continuously rotate a fairly complex child icon widget, passing that expensive child through the dedicated child parameter to avoid it being needlessly rebuilt from scratch on every single animation frame.

Common follow-ups: What is the difference between using AnimatedBuilder and simply calling setState directly inside an animation listener?;How does this specific optimization pattern relate to how the child parameter works on other custom widgets?