Creating Sequential and Parallel Animations in Flutter

Flutter, Google’s UI toolkit, offers powerful animation capabilities, enabling developers to create engaging and delightful user experiences. One common requirement is orchestrating animations in sequences or in parallel. Combining sequential and parallel animations effectively can make your app’s UI feel more polished and interactive.

Understanding Sequential Animations

Sequential animations are animations that run one after another. In Flutter, this can be achieved using the Future.delayed function to time the start of subsequent animations or by leveraging animation controllers effectively.

Understanding Parallel Animations

Parallel animations are animations that run simultaneously. This can be accomplished using multiple animation controllers controlled within a single AnimatedBuilder or through more advanced techniques like TweenAnimationBuilder.

Why Combine Sequential and Parallel Animations?

  • Improved User Experience: Combining animations provides more dynamic and interesting effects.
  • Enhanced UI Polish: Makes the application feel more refined and interactive.
  • Effective Information Delivery: Can guide the user through different steps or pieces of information in a structured and visually appealing manner.

Implementing Sequential Animations in Flutter

To create sequential animations, follow these steps:

Step 1: Set up AnimationController

Initialize an AnimationController for each animation sequence. The AnimationController manages the animation’s duration and provides the necessary hooks for starting, stopping, and reversing the animation.


import 'package:flutter/material.dart';

class SequentialAnimationExample extends StatefulWidget {
  @override
  _SequentialAnimationExampleState createState() => _SequentialAnimationExampleState();
}

class _SequentialAnimationExampleState extends State with TickerProviderStateMixin {
  late AnimationController _controller1;
  late AnimationController _controller2;
  late Animation<double> _animation1;
  late Animation<double> _animation2;

  @override
  void initState() {
    super.initState();

    // Controller 1 for the first animation
    _controller1 = AnimationController(
      duration: const Duration(seconds: 2),
      vsync: this,
    );

    // Controller 2 for the second animation
    _controller2 = AnimationController(
      duration: const Duration(seconds: 2),
      vsync: this,
    );

    // Animation 1: Scale up
    _animation1 = Tween<double>(begin: 0.0, end: 1.0).animate(_controller1);

    // Animation 2: Fade out
    _animation2 = Tween<double>(begin: 1.0, end: 0.0).animate(_controller2);

    // Add listeners to start the next animation after the previous completes
    _controller1.addStatusListener((status) {
      if (status == AnimationStatus.completed) {
        _controller2.forward();
      }
    });
  }

  @override
  void dispose() {
    _controller1.dispose();
    _controller2.dispose();
    super.dispose();
  }

  // ...
}

Step 2: Define Animations

Define the animations using Tween and Animation objects. Tween defines the beginning and ending values of the animation, while Animation links the Tween to the AnimationController.


    _animation1 = Tween<double>(begin: 0.0, end: 1.0).animate(_controller1);
    _animation2 = Tween<double>(begin: 1.0, end: 0.0).animate(_controller2);

Step 3: Chain Animations

Chain animations by listening to the status of the AnimationController. When the first animation completes, start the second animation.


    _controller1.addStatusListener((status) {
      if (status == AnimationStatus.completed) {
        _controller2.forward();
      }
    });

Step 4: Build the UI

Create the UI using AnimatedBuilder to reflect the changes in animation values. This ensures that the UI updates smoothly during the animation.


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Sequential Animations'),
      ),
      body: Center(
        child: AnimatedBuilder(
          animation: Listenable.merge([_animation1, _animation2]),
          builder: (context, child) {
            return Opacity(
              opacity: _animation2.value, // Fade Out
              child: Transform.scale(
                scale: _animation1.value, // Scale Up
                child: Container(
                  width: 100,
                  height: 100,
                  color: Colors.blue,
                ),
              ),
            );
          },
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          _controller1.forward(from: 0.0);
        },
        child: Icon(Icons.play_arrow),
      ),
    );
  }

Implementing Parallel Animations in Flutter

For parallel animations, use multiple animations with a single AnimatedBuilder or use TweenAnimationBuilder. Here’s how to achieve parallel animations using a single AnimatedBuilder:

Step 1: Set up AnimationControllers

Initialize multiple AnimationController instances, one for each animation you want to run in parallel.


import 'package:flutter/material.dart';

class ParallelAnimationExample extends StatefulWidget {
  @override
  _ParallelAnimationExampleState createState() => _ParallelAnimationExampleState();
}

class _ParallelAnimationExampleState extends State with TickerProviderStateMixin {
  late AnimationController _controller;
  late Animation<double> _animation1;
  late Animation<Color?> _animation2;

  @override
  void initState() {
    super.initState();

    _controller = AnimationController(
      duration: const Duration(seconds: 3),
      vsync: this,
    );

    // Animation 1: Rotation
    _animation1 = Tween<double>(begin: 0.0, end: 1.0).animate(
      CurvedAnimation(parent: _controller, curve: Curves.easeInOut),
    );

    // Animation 2: Color change
    _animation2 = ColorTween(begin: Colors.blue, end: Colors.red).animate(_controller);
  }

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

  // ...
}

Step 2: Define Animations

Create animation objects that define the properties you want to animate. Use Tween to specify the start and end values.


    _animation1 = Tween<double>(begin: 0.0, end: 1.0).animate(
      CurvedAnimation(parent: _controller, curve: Curves.easeInOut),
    );

    _animation2 = ColorTween(begin: Colors.blue, end: Colors.red).animate(_controller);

Step 3: Use AnimatedBuilder

Use AnimatedBuilder to apply both animations simultaneously. This allows multiple properties to change in parallel based on the same AnimationController.


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Parallel Animations'),
      ),
      body: Center(
        child: AnimatedBuilder(
          animation: _controller,
          builder: (context, child) {
            return Transform.rotate(
              angle: _animation1.value * 2 * 3.14,
              child: Container(
                width: 100,
                height: 100,
                color: _animation2.value,
              ),
            );
          },
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          _controller.repeat();
        },
        child: Icon(Icons.play_arrow),
      ),
    );
  }

Combining Sequential and Parallel Animations

Combining sequential and parallel animations involves nesting the concepts we’ve discussed. Start a parallel animation within a sequence or vice versa to achieve complex effects.

Example:

Here’s an example of a sequence where, after a delay, a parallel animation starts:


import 'package:flutter/material.dart';

class CombinedAnimationExample extends StatefulWidget {
  @override
  _CombinedAnimationExampleState createState() => _CombinedAnimationExampleState();
}

class _CombinedAnimationExampleState extends State with TickerProviderStateMixin {
  late AnimationController _controller1;
  late AnimationController _controller2;
  late Animation<double> _animationScale;
  late Animation<Color?> _animationColor;

  @override
  void initState() {
    super.initState();

    // Controller for scale animation
    _controller1 = AnimationController(
      duration: const Duration(seconds: 2),
      vsync: this,
    );

    // Controller for parallel animations (scale and color)
    _controller2 = AnimationController(
      duration: const Duration(seconds: 3),
      vsync: this,
    );

    // Scale animation
    _animationScale = Tween<double>(begin: 0.0, end: 1.0).animate(
      CurvedAnimation(parent: _controller2, curve: Curves.easeInOut),
    );

    // Color animation
    _animationColor = ColorTween(begin: Colors.blue, end: Colors.green).animate(_controller2);

    // Start the parallel animations after a delay
    Future.delayed(const Duration(seconds: 2), () {
      _controller2.forward();
    });
  }

  @override
  void dispose() {
    _controller1.dispose();
    _controller2.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Combined Animations'),
      ),
      body: Center(
        child: AnimatedBuilder(
          animation: Listenable.merge([_controller2]),
          builder: (context, child) {
            return Transform.scale(
              scale: _animationScale.value,
              child: Container(
                width: 100,
                height: 100,
                color: _animationColor.value,
              ),
            );
          },
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          _controller2.reset();
          Future.delayed(const Duration(seconds: 1), () {
            _controller2.forward();
          });
        },
        child: Icon(Icons.play_arrow),
      ),
    );
  }
}

Conclusion

Combining sequential and parallel animations in Flutter allows you to create sophisticated and engaging user interfaces. By using AnimationController, Tween, AnimatedBuilder, and careful timing with Future.delayed, you can craft visually appealing and interactive experiences in your Flutter apps.