Creating Custom Animations in Flutter
Flutter
Animations

Creating Custom Animations in Flutter

Diluk Udayakantha

Diluk Udayakantha

Flutter Developer

Feb 10, 2025•6 min read

Animations are a crucial part of modern mobile applications, enhancing user experience and providing visual feedback. Flutter provides a powerful and flexible animation system that allows developers to create beautiful, custom animations. This article will take you through Flutter's animation framework and show you how to build impressive custom animations.

Understanding Flutter's Animation System

Flutter's animation system is based on the Animation class, which represents a value that changes over time. Before diving into code examples, let's understand the key components:

  • Animation: A core class that understands interpolation and state (completed, dismissed)
  • AnimationController: Controls the animation (play, pause, reverse, etc.)
  • Tween: Maps the animation progress to a range of values
  • AnimatedBuilder/AnimatedWidget: Widgets that rebuild when animations change

1. Basic Animation Using AnimationController

Let's start with a simple animation that scales a container:

class ScaleAnimationDemo extends StatefulWidget {
  @override
  _ScaleAnimationDemoState createState() => _ScaleAnimationDemoState();
}

class _ScaleAnimationDemoState extends State 
    with SingleTickerProviderStateMixin {
  
  late AnimationController _controller;
  late Animation _animation;

  @override
  void initState() {
    super.initState();
    _controller = AnimationController(
      duration: Duration(seconds: 2),
      vsync: this,
    );
    
    _animation = Tween(begin: 0, end: 200).animate(_controller)
      ..addListener(() {
        setState(() {});  // Trigger rebuild when animation changes
      });
      
    _controller.forward();  // Start the animation
  }

  @override
  void dispose() {
    _controller.dispose();  // Important to dispose controllers
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Container(
        width: _animation.value,
        height: _animation.value,
        color: Colors.blue,
      ),
    );
  }
}
          

In this example, we're creating an animation that changes a value from 0 to 200 over 2 seconds, and we're using that value to set the dimensions of our container.

2. Using AnimatedBuilder for Cleaner Code

The previous example works but using setState for animation isn't optimal. AnimatedBuilder provides a more efficient way:

class ImprovedScaleAnimation extends StatefulWidget {
  @override
  _ImprovedScaleAnimationState createState() => _ImprovedScaleAnimationState();
}

class _ImprovedScaleAnimationState extends State
    with SingleTickerProviderStateMixin {
  
  late AnimationController _controller;
  late Animation _animation;

  @override
  void initState() {
    super.initState();
    _controller = AnimationController(
      duration: Duration(seconds: 2),
      vsync: this,
    );
    
    _animation = Tween(begin: 0, end: 200).animate(_controller);
    _controller.forward();
  }

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

  @override
  Widget build(BuildContext context) {
    return AnimatedBuilder(
      animation: _animation,
      builder: (context, child) {
        return Center(
          child: Container(
            width: _animation.value,
            height: _animation.value,
            color: Colors.green,
            child: child,
          ),
        );
      },
      child: Center(
        child: Text('Animated!', style: TextStyle(color: Colors.white)),
      ),
    );
  }
}
          

AnimatedBuilder rebuilds only the parts affected by the animation, not the entire widget tree. The child parameter is particularly useful because it's built only once and reused.

3. Creating Complex Animations with Curves

Animations don't have to be linear. Flutter provides various curves to control the rate of change:

// Creating a curved animation
_animation = Tween(begin: 0, end: 200).animate(
  CurvedAnimation(
    parent: _controller,
    curve: Curves.elasticOut,
  ),
);
          

Some commonly used curves include:

  • Curves.linear: Constant rate of change
  • Curves.easeIn: Starts slowly, speeds up
  • Curves.easeOut: Starts quickly, slows down
  • Curves.bounceOut: Adds a bouncing effect at the end
  • Curves.elasticIn: Creates an elastic effect at the start

4. Staggered Animations

Staggered animations involve multiple animations that start at different times but are controlled by a single controller:

class StaggeredAnimationDemo extends StatefulWidget {
  @override
  _StaggeredAnimationDemoState createState() => _StaggeredAnimationDemoState();
}

class _StaggeredAnimationDemoState extends State
    with SingleTickerProviderStateMixin {
  
  late AnimationController _controller;
  late Animation _opacity;
  late Animation _width;
  late Animation _height;
  late Animation _padding;
  late Animation _borderRadius;
  late Animation _color;

  @override
  void initState() {
    super.initState();
    _controller = AnimationController(
      duration: Duration(seconds: 4),
      vsync: this,
    );
    
    // Defining intervals for each animation in the sequence
    _opacity = Tween(begin: 0.0, end: 1.0)
        .animate(CurvedAnimation(
          parent: _controller,
          curve: Interval(0.0, 0.25, curve: Curves.ease),
        ));
        
    _width = Tween(begin: 50.0, end: 200.0)
        .animate(CurvedAnimation(
          parent: _controller,
          curve: Interval(0.25, 0.5, curve: Curves.ease),
        ));
        
    _height = Tween(begin: 50.0, end: 200.0)
        .animate(CurvedAnimation(
          parent: _controller,
          curve: Interval(0.5, 0.75, curve: Curves.ease),
        ));
        
    _padding = EdgeInsetsTween(
      begin: EdgeInsets.only(bottom: 16.0),
      end: EdgeInsets.only(bottom: 75.0),
    ).animate(CurvedAnimation(
      parent: _controller,
      curve: Interval(0.5, 0.75, curve: Curves.ease),
    ));
    
    _borderRadius = BorderRadiusTween(
      begin: BorderRadius.circular(4.0),
      end: BorderRadius.circular(75.0),
    ).animate(CurvedAnimation(
      parent: _controller,
      curve: Interval(0.75, 1.0, curve: Curves.ease),
    ));
    
    _color = ColorTween(
      begin: Colors.blue,
      end: Colors.purple,
    ).animate(CurvedAnimation(
      parent: _controller,
      curve: Interval(0.75, 1.0, curve: Curves.ease),
    ));
    
    _controller.forward();
  }

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

  @override
  Widget build(BuildContext context) {
    return AnimatedBuilder(
      animation: _controller,
      builder: (context, child) {
        return Center(
          child: Opacity(
            opacity: _opacity.value,
            child: Container(
              width: _width.value,
              height: _height.value,
              padding: _padding.value,
              decoration: BoxDecoration(
                color: _color.value,
                borderRadius: _borderRadius.value,
              ),
              child: child,
            ),
          ),
        );
      },
      child: Center(
        child: Text(
          'Staggered Animation',
          style: TextStyle(color: Colors.white),
          textAlign: TextAlign.center,
        ),
      ),
    );
  }
}
          

In this example, we've created multiple animations with different intervals, all controlled by a single AnimationController. This creates a sequence of animations that flow naturally from one to another.

5. Custom Tween Classes

For complex animations that involve custom objects, you can create your own Tween class:

class MyPosition {
  final double x, y;
  MyPosition(this.x, this.y);
}

class MyPositionTween extends Tween {
  MyPositionTween({MyPosition? begin, MyPosition? end})
      : super(begin: begin, end: end);

  @override
  MyPosition lerp(double t) {
    return MyPosition(
      begin!.x + (end!.x - begin!.x) * t,
      begin!.y + (end!.y - begin!.y) * t,
    );
  }
}

// Usage:
final animation = MyPositionTween(
  begin: MyPosition(0, 0),
  end: MyPosition(100, 200),
).animate(_controller);
          

6. Using Hero Animations for Transitions

Hero animations create a visual connection between different screens:

// On the first screen
Hero(
  tag: 'imageHero',
  child: Image.asset('assets/my_image.png'),
)

// On the second screen
Hero(
  tag: 'imageHero',
  child: Image.asset('assets/my_image.png'),
)
          

With the same tag, Flutter will animate the image from one screen to another during navigation.

7. Custom Animated Widgets

For reusable animated components, create custom animated widgets:

class PulsatingCircle extends StatefulWidget {
  final Color color;
  final double size;
  
  const PulsatingCircle({
    Key? key,
    this.color = Colors.blue,
    this.size = 100.0,
  }) : super(key: key);

  @override
  _PulsatingCircleState createState() => _PulsatingCircleState();
}

class _PulsatingCircleState extends State
    with SingleTickerProviderStateMixin {
  
  late AnimationController _controller;
  late Animation _animation;

  @override
  void initState() {
    super.initState();
    _controller = AnimationController(
      duration: Duration(seconds: 2),
      vsync: this,
    )..repeat(reverse: true);
    
    _animation = Tween(begin: 1.0, end: 1.5)
        .animate(CurvedAnimation(
          parent: _controller,
          curve: Curves.easeInOut,
        ));
  }

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

  @override
  Widget build(BuildContext context) {
    return AnimatedBuilder(
      animation: _animation,
      builder: (context, child) {
        return Transform.scale(
          scale: _animation.value,
          child: Container(
            width: widget.size,
            height: widget.size,
            decoration: BoxDecoration(
              color: widget.color.withOpacity(1.0 / _animation.value),
              shape: BoxShape.circle,
            ),
          ),
        );
      },
    );
  }
}
          

This creates a reusable pulsating circle widget that you can use anywhere in your app.

8. Implicit Animations

For simpler cases, Flutter provides built-in implicit animation widgets like AnimatedContainer:

class ImplicitAnimationDemo extends StatefulWidget {
  @override
  _ImplicitAnimationDemoState createState() => _ImplicitAnimationDemoState();
}

class _ImplicitAnimationDemoState extends State {
  bool _isExpanded = false;

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () {
        setState(() {
          _isExpanded = !_isExpanded;
        });
      },
      child: Center(
        child: AnimatedContainer(
          duration: Duration(seconds: 1),
          curve: Curves.easeInOut,
          width: _isExpanded ? 200.0 : 100.0,
          height: _isExpanded ? 200.0 : 100.0,
          color: _isExpanded ? Colors.purple : Colors.blue,
          child: Center(
            child: Text(
              'Tap me',
              style: TextStyle(color: Colors.white),
            ),
          ),
        ),
      ),
    );
  }
}
          

Some other useful implicit animation widgets include:

  • AnimatedOpacity: Animate changes in opacity
  • AnimatedPadding: Animate padding changes
  • AnimatedPositioned: Animate position in a Stack
  • AnimatedSwitcher: Animate between different widgets
  • AnimatedCrossFade: Crossfade between two widgets

9. Combining Animations with Physics

Flutter's physics simulation can create natural-feeling animations:

// Spring animation
final SpringSimulation spring = SpringSimulation(
  SpringDescription(
    mass: 1.0,
    stiffness: 100.0,
    damping: 10.0,
  ),
  0.0, // Starting position
  1.0, // Ending position
  0.0, // Starting velocity
);

_controller = AnimationController(vsync: this)
  ..animateWith(spring);
          

10. Lottie Animations

For complex animations designed in After Effects, use the Lottie package:

// Add to pubspec.yaml:
// dependencies:
//   lottie: ^1.4.3

// In your widget:
import 'package:lottie/lottie.dart';

// Simple usage
Lottie.asset('assets/animation.json')

// Controlled animation
Lottie.asset(
  'assets/animation.json',
  controller: _controller,
  onLoaded: (composition) {
    _controller.duration = composition.duration;
    _controller.forward();
  },
)
          

Best Practices for Flutter Animations

  1. Keep animations subtle and purposeful. Animations should enhance UX, not distract from it.
  2. Use AnimatedBuilder or AnimatedWidget instead of setState for better performance.
  3. Always dispose of your AnimationControllers to prevent memory leaks.
  4. Test animations on lower-end devices to ensure they run smoothly.
  5. Consider using simpler implicit animations when they meet your needs.
  6. Use Hero animations to create visual continuity between screens.
  7. For complex animations, break them down into smaller, composable parts.

Conclusion

Flutter's animation system provides incredible flexibility for creating engaging user experiences. By understanding the core concepts of AnimationController, Tween, and various animation widgets, you can build beautiful, custom animations that make your app stand out.

Start with simple animations and gradually explore more complex techniques as you become comfortable with the system. Remember that great animations enhance the user experience without calling too much attention to themselves.

With the techniques covered in this article, you now have a solid foundation to create stunning animations in your Flutter applications.