Flutter Animations

5 min

5 min

Flutter Research at Blup

Ashutosh Rawat

Published on Jun 7, 2024

Flutter Animations: How to Animate the Properties of a Container in Flutter.

Animate container properties in Flutter for dynamic user experiences. Step-by-step guide for StatefulWidget, AnimatedContainer, and triggering animations.
Animate container properties in Flutter for dynamic user experiences. Step-by-step guide for StatefulWidget, AnimatedContainer, and triggering animations.

Introduction

Welcome to another exciting installment of our Flutter learning roadmap series! In this article, we'll delve into the world of Flutter animations and Transitions, specifically focusing on animating container properties.

Animations play a crucial role in creating engaging user experiences in mobile applications. They add flair, interactivity, and a touch of magic to your app, making it more dynamic and appealing to users. Flutter, with its powerful animation framework, offers developers a wide range of tools and techniques to easily create stunning animations.

Before we dive into the details of animating container properties, let's explore some intriguing facts about animations:

  • Animations can significantly improve user engagement and retention in mobile apps.

  • Popular apps like Instagram, TikTok, and Uber seamlessly integrate animations to enhance the user experience.

  • The integration of animations is a fundamental aspect of modern app design.

These questions set the stage for our exploration into Flutter animations. So, buckle up as we journey to uncover the secrets of animating container properties in Flutter!

Animated Container

Animating container properties in Flutter adds an interactive and polished feel to your app. This guide delves into the advanced aspects of animating properties such as size, color, and border-radius using the AnimatedContainer widget. We'll cover creating a StatefulWidget, building an AnimatedContainer, triggering animations, and optimizing performance for a seamless user experience.

Contents

  1. Introduction to AnimatedContainer

  2. Creating a StatefulWidget with Default Properties

  3. Building an AnimatedContainer

  4. Triggering Animations

  5. Interactive Example

  6. Advanced Performance Tips

Introduction to AnimatedContainer

The Container class provides a convenient way to create a widget with specific properties such as width, height, background color, padding, and borders. To animate these properties, Flutter offers the AnimatedContainer widget. It allows you to define the width, height, background color, and other properties, automatically animating between the old and new values when rebuilt. These animations are known as "implicit animations" in Flutter.

This guide outlines the process of animating the size, background color, and border radius of a container when the user taps a button, following these steps:

  1. Establish a Stateful widget with default properties.

  2. Construct an Animated Container utilizing these properties.

  3. Initiate the animation by rebuilding the container with updated properties.

Creating a StatefulWidget with Default Properties

In Flutter, animations are achieved by updating the properties of widgets over time. Before diving into animating container properties, let's set up a StatefulWidget with default properties that we can later animate.

class MyAnimatedContainer extends StatefulWidget {
  @override
  _MyAnimatedContainerState createState() => _MyAnimatedContainerState();
}

class _MyAnimatedContainerState extends State<MyAnimatedContainer> {
  // Default properties
  double _width = 100.0;
  double _height = 100.0;
  Color _color = Colors.blue;

  @override
  Widget build(BuildContext context) {
    // Widget structure
    return Container(
      width: _width,
      height: _height,
      color: _color,
    );
  }
}

In this code snippet, we define a StatefulWidget named MyAnimatedContainer. Inside its state class _MyAnimatedContainerState, we initialize three properties: _width, _height, and _color, with default values representing the initial size and color of the container.

The build method returns a Container widget with the specified width, height, and color properties. At this stage, the container remains static, but we'll soon enhance it to animate its properties dynamically.

Explanation:

  • MyAnimatedContainer: This is a StatefulWidget that will serve as the foundation for our animated container.

  • _MyAnimatedContainerState: The state class for MyAnimatedContainer, where we'll manage the dynamic behavior of the widget.

  • _width, _height, _color: These are the properties representing the dimensions and color of the container. We initialize them with default values.

  • build method: Returns a Container widget with the specified width, height, and color properties. At this stage, the container is static and does not animate.

By setting up this StatefulWidget with default properties, we've laid the groundwork for animating its properties in the subsequent sections. Now, let's proceed to enhance this widget to enable smooth animations of its properties.

Building an Animated Container

In Flutter, animating container properties is made remarkably simple with the AnimatedContainer widget. This widget not only provides a smooth transition between property changes but also eliminates the need for complex animation logic. Let's dive into building an AnimatedContainer and understand its implementation with a detailed code example.

AnimatedContainer(
  // Use the properties stored in the State class.
  width: _width,
  height: _height,
  decoration: BoxDecoration(
    color: _color,
    borderRadius: _borderRadius,
  ),
  // Define how long the animation should take.
  duration: const Duration(seconds: 1),
  // Provide an optional curve to make the animation feel smoother.
  curve: Curves.fastOutSlowIn,
)

Explanation:

StatefulWidget:

We start by defining a StatefulWidget called AnimatedContainerExample. This widget will manage the state of our animated container.

State:

Inside the state class _AnimatedContainerExampleState, we declare variables _width, _height, and _color to control the properties of our container.

GestureDetector:

We wrap our AnimatedContainer with a GestureDetector to detect taps. Upon tapping, we trigger a state change using setState.

AnimatedContainer:

The core of our animation lies within the AnimatedContainer widget. We specify its properties such as duration and curve to define the animation's duration and easing curve, respectively.

  • duration: This property determines how long the animation will take to complete. In our example, we set it to 1 second.

  • curve: The curve property defines the rate of change of an animation over time. We use Curves.easeInOut for a smooth acceleration and deceleration effect.

Inside the AnimatedContainer, we specify the dynamic properties that we want to animate:

  • width: Controls the width of the container. When tapped, it transitions from 100.0 to 200.0.

  • height: Similarly, controls the height of the container.

  • color: Determines the background color of the container. Upon tap, it changes from blue to green.

Additionally, we include a child widget containing a simple text ('Tap Me') to demonstrate that the animation encompasses the container and its contents.

Triggering the Animations

In Flutter, animations are often initiated by rebuilding widgets with updated properties. This allows for seamless transitions and dynamic visual effects. Let's explore how we can start animations by rebuilding a container with new properties.

FloatingActionButton(
  // Triggered when the user taps the button
  onPressed: () {
    // Use setState to rebuild the widget with new values
    setState(() {
      // Create a random number generator
      final random = Random();

      // Generate random width and height
      _width = random.nextInt(300).toDouble();
      _height = random.nextInt(300).toDouble();

      // Generate a random color
      _color = Color.fromRGBO(
        random.nextInt(256),
        random.nextInt(256),
        random.nextInt(256),
        1,
      );

      // Generate a random border radius
      _borderRadius =
          BorderRadius.circular(random.nextInt(100).toDouble());
    });
  },
  // Icon for the floating action button
  child: const Icon(Icons.play_arrow),
)

In this code snippet, we utilize a FloatingActionButton as a trigger for initiating the animation. When the button is pressed, the onPressed callback is invoked. Within this callback, we call setState, which notifies Flutter to rebuild the widget with new properties.

Using a random number generator, we dynamically generate new values for properties such as width, height, color, and border radius. These new values result in a visually appealing animation as the container transitions to its updated state.

Interactive Example

Elevating Your UI with Flutter Animations

To truly grasp the power of Flutter animations, let's dive into an interactive example where we'll dynamically animate the properties of a container. This hands-on demo will not only illustrate the principles discussed but also serve as a playground for you to experiment with animations in Flutter.

import 'dart:math';

import 'package:flutter/material.dart';

void main() => runApp(const AnimatedContainerApp());

class AnimatedContainerApp extends StatefulWidget {
  const AnimatedContainerApp({super.key});

  @override
  State<AnimatedContainerApp> createState() => _AnimatedContainerAppState();
}

class _AnimatedContainerAppState extends State<AnimatedContainerApp> {
  // Define the various properties with default values. Update these properties
  // when the user taps a FloatingActionButton.
  double _width = 50;
  double _height = 50;
  Color _color = Colors.green;
  BorderRadiusGeometry _borderRadius = BorderRadius.circular(8);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('AnimatedContainer Demo'),
        ),
        body: Center(
          child: AnimatedContainer(
            // Use the properties stored in the State class.
            width: _width,
            height: _height,
            decoration: BoxDecoration(
              color: _color,
              borderRadius: _borderRadius,
            ),
            // Define how long the animation should take.
            duration: const Duration(seconds: 1),
            // Provide an optional curve to make the animation feel smoother.
            curve: Curves.fastOutSlowIn,
          ),
        ),
        floatingActionButton: FloatingActionButton(
          // When the user taps the button
          onPressed: () {
            // Use setState to rebuild the widget with new values.
            setState(() {
              // Create a random number generator.
              final random = Random();

              // Generate a random width and height.
              _width = random.nextInt(300).toDouble();
              _height = random.nextInt(300).toDouble();

              // Generate a random color.
              _color = Color.fromRGBO(
                random.nextInt(256),
                random.nextInt(256),
                random.nextInt(256),
                1,
              );

              // Generate a random border radius.
              _borderRadius =
                  BorderRadius.circular(random.nextInt(100).toDouble());
            });
          },
          child: const Icon(Icons.play_arrow),
        ),
      ),
    );
  }
}

In this interactive example, we've created a Flutter app that showcases the AnimatedContainer widget in action. Here's how it works:

  • Default Properties: Initially, the container has default properties: width of 50, height of 50, green color, and a border radius of 8.

  • Animation Trigger: Tapping on the floating action button triggers an animation. Each tap randomly generates new values for width, height, color, and border-radius, resulting in a visually stunning animation.

  • Smooth Animation: We've specified 1 second for the animation, ensuring a smooth transition between property changes. Additionally, we've used the Curves.fastOutSlowIn curve to make the animation feel more natural.

  • Endless Possibilities: Feel free to experiment with the code! Adjust the animation duration, try different curves, or modify the range of random values to see how it affects the animation.

Advanced Performance Tips

As you delve deeper into Flutter animation development, optimizing performance becomes crucial for delivering smooth and responsive user experiences. Here are some advanced performance tips to consider when animating the properties of a container in Flutter:

  1. Minimize Rebuilds: Animations in Flutter often involve rebuilding widgets with new properties. To minimize unnecessary rebuilds, leverage techniques like ValueNotifier or AnimatedBuilder to only rebuild the parts of your UI that need updating.

  2. Use AnimatedBuilder Wisely: While AnimatedContainer simplifies animating container properties, sometimes you may need more control over the animation process. In such cases, use AnimatedBuilder to manually define your animation logic and avoid unnecessary widget rebuilds.

  3. Optimize Rendering: To improve rendering performance, consider using the shouldRepaint parameter in custom-painted widgets. This parameter allows you to specify conditions under which the widget should be repainted, reducing unnecessary repaints during animations.

  4. Leverage Hardware Acceleration: Flutter leverages hardware acceleration to optimize rendering performance. Ensure that your animations benefit from hardware acceleration by avoiding heavy computations within the UI thread and minimizing the use of expensive widgets.

  5. Use Tween Animations: Tween animations interpolate between a range of values over a specified duration, offering smoother animations compared to linear changes. Utilize Tween animations for transforming container properties like size, position, and opacity, ensuring a visually appealing user experience.

  6. Offload Complex Animations: For complex animations involving heavy computations or frequent updates, consider offloading the animation logic to a separate isolate using packages like flutter_bloc or provider. This approach prevents UI jank and ensures consistent performance across different devices.

  7. Profile and Optimize: Use Flutter's built-in performance tools like the Flutter DevTools to profile your animations and identify performance bottlenecks. Analyze rendering metrics, CPU usage, and memory allocation to optimize your animations for maximum efficiency.

  8. Cache Render Objects: If your animation involves complex layouts or expensive computations, consider caching render objects using the RepaintBoundary widget. Caching render objects minimizes the performance impact of rebuilding the widget tree during animations.

By implementing these advanced performance tips, you can optimize your Flutter animations for smooth, responsive, and efficient user experiences. Remember to profile your animations regularly and fine-tune your code to achieve optimal performance across various devices and screen sizes.

Flutter Learning Resources

Introduction to Animations in Flutter

Understand the foundational concepts of animations in Flutter, including Tweens, Animation, and AnimationController. Explore the differences between implicit and explicit animations.

Read More: Introduction to Animations in Flutter

Exploring Implicit Animations in Flutter

Delve into implicit animations and their associated widgets like AnimatedOpacity, AnimatedPadding, and AnimatedAlign. Learn how to create smooth animations without explicitly managing animation controllers.

Read More: Exploring Implicit Animations in Flutter

Diving into Explicit Animations in Flutter

Differentiate between implicit and explicit animations while exploring core components like AnimationController, Animation, and Tween. Gain a deeper understanding of managing animations programmatically.

Read More: Diving into Explicit Animations in Flutter

Advanced Animation Techniques in Flutter

Master advanced animation techniques such as animating multiple properties with TweenSequence and Interval. Create complex animation sequences with staggered animations and develop custom animated widgets.

Read More: Advanced Animation Techniques in Flutter

Leveraging Animation Libraries in Flutter

Discover popular animation libraries like flutter_animate and Rive. Learn basic setup and examples using flutter_animate, and integrate Rive animations seamlessly into your Flutter apps.

Read More: Leveraging Animation Libraries in Flutter

Creating Seamless Transition Animations in Flutter

Explore the art of creating seamless page transitions and custom transitions. Utilize PageRouteBuilder for custom transitions and leverage Hero widgets for smooth shared element transitions.

Read More: Creating Seamless Transition Animations in Flutter

Optimizing Animation Performance in Flutter

Identify common performance bottlenecks in Flutter animations and learn techniques for optimizing animations to ensure smooth performance. Utilize Flutter's performance tools to monitor and improve animation performance.

Read More: Optimizing Animation Performance in Flutter

Real-world Examples and Case Studies

Analyze real-world examples of Flutter animations in popular apps, including weather apps and productivity apps. Explore complex transitions and discover best practices learned from real-world implementation.

Read More: Real-World Examples and Case Studies of Flutter Animations

This comprehensive guide will equip you with the knowledge and skills needed to master Flutter animations and create captivating user experiences in your Flutter apps. Explore each section to delve deeper into the world of Flutter animations.

Conclusion

Animation is the pulse that breathes life into your Flutter applications, transforming static elements into dynamic experiences. With Flutter's AnimatedContainer, you have the power to animate container properties seamlessly, opening the door to endless possibilities for engaging user interfaces.

But don't stop here. Dive deeper into the world of Flutter animation on blup.in, where you'll find a treasure trove of resources, tutorials, and community insights to fuel your animation journey.

Embrace the art of animation, experiment with new techniques, and push the boundaries of what's possible in Flutter. Let your creativity soar as you craft immersive experiences that leave a lasting impression on users.

So, what are you waiting for? Head over to blup.in and unleash the full potential of animation in your Flutter apps. Your users will thank you for it. Happy animating!

Follow us on

Follow us on