LibraryAnimatedBuilder and AnimatedWidget

AnimatedBuilder and AnimatedWidget

Learn about AnimatedBuilder and AnimatedWidget as part of Flutter App Development with Dart

Flutter UI Animations: AnimatedBuilder and AnimatedWidget

Flutter's declarative UI paradigm makes building beautiful and interactive user interfaces a joy. Animations are a key component in creating engaging user experiences. This module will explore two fundamental Flutter widgets for animation:

code
AnimatedBuilder
and
code
AnimatedWidget
.

Understanding Flutter Animations

Flutter animations are typically driven by

code
Animation
objects, which represent a value that changes over a period of time. These
code
Animation
objects are often managed by
code
AnimationController
s. To make these changing values visible in the UI, we need widgets that can rebuild themselves whenever the animation's value changes. This is where
code
AnimatedBuilder
and
code
AnimatedWidget
come in.

AnimatedBuilder: Efficiently Rebuilding UI

code
AnimatedBuilder
is a widget that takes an
code
Animation
and a builder function. It listens to the animation and rebuilds its child whenever the animation's value changes. The key advantage of
code
AnimatedBuilder
is its efficiency: it only rebuilds the part of the widget tree specified by its
code
builder
function, rather than rebuilding the entire widget tree.

AnimatedBuilder rebuilds only specified parts of the UI.

Use AnimatedBuilder when you have a complex widget tree and only a small portion needs to animate. It takes an animation and a builder function that returns the widget to be animated.

The AnimatedBuilder widget is a powerful tool for optimizing animation performance in Flutter. It accepts an Animation<T> object and a builder callback. The builder callback receives the animation object and returns the widget subtree that should be rebuilt. AnimatedBuilder automatically subscribes to the animation, ensuring that the builder is called whenever the animation's value changes. This selective rebuilding prevents unnecessary rebuilds of other parts of your application, leading to smoother animations and better performance, especially in complex UIs.

AnimatedWidget: A Simpler Approach

code
AnimatedWidget
is an abstract class that you can extend to create custom animated widgets. It automatically listens to an
code
Animation
passed to its constructor and calls its
code
build
method whenever the animation's value changes. While simpler to implement for custom animations, it might rebuild more than necessary if not carefully managed.

AnimatedWidget is a base class for custom animated widgets.

Extend AnimatedWidget to create your own animated components. It automatically handles listening to an animation and rebuilding.

When you need to create a custom widget that animates based on an Animation object, extending AnimatedWidget is a straightforward approach. You provide the Animation to the superclass constructor. The AnimatedWidget base class then manages the listener, ensuring that your custom build method is invoked whenever the animation's value updates. This pattern is useful for encapsulating specific animation behaviors into reusable widgets.

When to Use Which?

FeatureAnimatedBuilderAnimatedWidget
Primary UseEfficiently rebuilds specific parts of a widget tree.Base class for creating custom animated widgets.
EfficiencyHigh; rebuilds only the builder's subtree.Can be less efficient if not managed carefully; rebuilds the entire widget extending it.
ImplementationComposition: wraps existing widgets.Inheritance: extends the class to create new widgets.
FlexibilityVery flexible for animating any widget subtree.Best for creating reusable, self-contained animated components.

For most common animation scenarios where you want to animate a specific property of an existing widget (like rotation, scaling, or color), AnimatedBuilder is the preferred and more performant choice.

Example: Animating a Rotating Container

Let's consider how to animate a

code
Container
to rotate using
code
AnimatedBuilder
.

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Rotation Animation',
      home: RotationScreen(),
    );
  }
}

class RotationScreen extends StatefulWidget {
  @override
  _RotationScreenState createState() => _RotationScreenState();
}

class _RotationScreenState extends State<RotationScreen> with SingleTickerProviderStateMixin {
  late AnimationController _controller;
  late Animation<double> _animation;

  @override
  void initState() {
    super.initState();
    _controller = AnimationController(
      duration: const Duration(seconds: 2),
      vsync: this,
    );
    _animation = Tween<double>(begin: 0.0, end: 2 * 3.14159).animate(_controller)
      ..addListener(() {
        setState(() {}); // Rebuilds the widget tree
      });
    _controller.repeat(); // Makes the animation loop
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('AnimatedBuilder Example')),
      body: Center(
        child: AnimatedBuilder(
          animation: _animation,
          builder: (BuildContext context, Widget? child) {
            return Transform.rotate(
              angle: _animation.value,
              child: child,
            );
          },
          child: Container(
            width: 200.0,
            height: 200.0,
            color: Colors.blue,
          ),
        ),
      ),
    );
  }
}

This code demonstrates using AnimatedBuilder to apply a rotation transformation to a Container. The _controller drives the animation from 0 to 2π (a full circle). The AnimatedBuilder listens to this animation and uses the builder function to apply the Transform.rotate widget with the current animation value. The child parameter of AnimatedBuilder is used to pass the static Container widget, which is only rebuilt when the animation changes, not on every setState call.

📚

Text-based content

Library pages focus on text content

What is the primary benefit of using AnimatedBuilder over a simple setState in a complex UI?

AnimatedBuilder efficiently rebuilds only the specified widget subtree, preventing unnecessary rebuilds of the entire widget tree, which leads to better performance.

Key Takeaways

Both

code
AnimatedBuilder
and
code
AnimatedWidget
are essential tools for creating animations in Flutter.
code
AnimatedBuilder
is generally preferred for its performance benefits in animating specific parts of your UI, while
code
AnimatedWidget
is useful for creating custom, reusable animated components.

Learning Resources

Flutter Animations: AnimatedBuilder(documentation)

Official Flutter documentation explaining the AnimatedBuilder widget and its usage for efficient UI updates during animations.

Flutter Animations: AnimatedWidget(documentation)

Official Flutter documentation detailing the AnimatedWidget abstract class for creating custom animated widgets.

Flutter Animations Tutorial(documentation)

A comprehensive guide to Flutter's animation system, covering controllers, tweens, and various animation widgets.

Flutter Animations: A Deep Dive(video)

A detailed video tutorial explaining Flutter's animation system, including practical examples of AnimatedBuilder.

Understanding Flutter's Animation System(blog)

A blog post that breaks down Flutter's animation controllers and tweens, foundational concepts for using AnimatedBuilder.

Flutter Animation Widget Examples(tutorial)

A hands-on tutorial from Flutter.dev that walks through building various animations, often utilizing AnimatedBuilder.

Flutter Animation Basics(video)

This video provides a solid introduction to Flutter's animation framework, explaining the core concepts that power widgets like AnimatedBuilder.

Flutter UI Animations: A Practical Guide(video)

A practical guide to building beautiful UI animations in Flutter, showcasing common patterns and widgets.

Flutter Animations: The Complete Guide(video)

A comprehensive guide covering various aspects of Flutter animations, including implicit and explicit animations.

Flutter Animation Controller Explained(video)

This video focuses on the AnimationController, a crucial component for managing animations that are then used with widgets like AnimatedBuilder.