Master Flutter Animation: Easy Steps to Add Simple Animation in Flutter

Add simple animation in Flutter

Written and reviewed by: 

SHARE

Animations are crucial to enhancing the user experience and raising the degree of interaction with mobile applications. Using Flutter, Google’s UI toolkit for building native applications for desktop, web, and mobile platforms, developers can produce incredible, one-of-a-kind animations.

The Basics of Flutter Animation:

An application is enjoyable to use when it contains interactive features and seamless transitions. On the other hand, badly designed animations have the power to ruin an application or give it an amateurish appearance. This means that any framework’s animation principles must be understood in order to improve the user experience.

Widget visual attributes like opacity, size, and position are controlled by animations, which are by definition sequences of values that change over time. The timing and duration of Flutter animations are controlled by an AnimationController. The AnimationController creates a stream of values that are received by an animation object. The animation modifies the widget’s visual properties by interpolating the values over time.

Usually, tweens or physics are the basis for Flutter animations. We’ll talk about these concepts and how they function in the sections that follow.

You can use the animation widgets that Flutter comes with in your app to create incredibly beautiful visualizations!

AnimatedAlign
AnimatedContainer
AnimatedOpacity
AnimatedPadding
AnimatedPositioning
AnimatedSize
AnimatedList
Animated Grid
Animated GridState
AnimatedCrossFade
AnimatedDefaultTextStyle
AnimatedListState
AnimatedModalBarrier
AnimatedPhysicalModel
AnimationStyle
AnimationMin
AnimationMean
AnimationMax
AnimationController
Animation
AnimatedWidgetBaseState
AnimatedSwitcher
AnimatedSlide

Flutter’s Animation Types:

There are some kinds of Flutter Animation:

1.Drawing Based

Drawing-based animation is created by an animation framework or custom painter. A popular animation framework is Rive, where we can create designs by hand drawing.

2. Code-Based

The goal of these animations is to animate the widgets that are currently available, such as the row, container, column, stack, etc. The widget’s scale, size, position, and other attributes are also modifiable.

An image of a product, for instance, can be moved from the shopping list to the cart icon. You can utilize explicit or implicit animations with Flutter’s code-based animations.

3. Implicit Animation

Technically speaking, these kinds of animations are classified as code-based animations. They are very simple to implement as compared to other types of animations.

Flutter’s animation library can be used to provide motion and visual effects to the UI widgets. You can use a single set of widgets from the library to handle animations. Using the Container class is a convenient way to create a widget with many parameters like width, height, background color, padding, borders, and more.

Simple animations often modify these parameters over time. For example, you could want to transition the backdrop color from red to blue to indicate that a user has selected an item.

Animated Container is the pre-built Flutter implicit animation widget. You can use it like the Container Widget. Here, you have to additionally set the duration of the animation. You can animate the containers width, height, background color, padding, border, etc.

Here are a few steps to animate a container by using Animated Container.
First of all, create a stateful widget, and then under the scaffold, select the Animated Container Widget. Then set the duration of the animation in the duration parameters. After that, make the container click-able by wrapping it with a gesture detector or inkwell widget. Use the OnTap function and give your logic to animate the container.

Here is an example of an animated container. Just go and run this code in your favourite code editor.

Dart
import 'package:flutter/material.dart';

/// Flutter code sample for [AnimatedContainer].

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

class AnimatedContainerExampleApp extends StatelessWidget {
  const AnimatedContainerExampleApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: const Text('AnimatedContainer Sample')),
        body: const AnimatedContainerExample(),
      ),
    );
  }
}

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

  @override
  State<AnimatedContainerExample> createState()
      _AnimatedContainerExampleState();
}

class _AnimatedContainerExampleState extends State<AnimatedContainerExample> {
  bool selected = false;

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () {
        setState(() {
          selected = !selected;
        });
      },
      child: Center(
        child: AnimatedContainer(
          width: selected ? 200.0 : 100.0,
          height: selected ? 100.0 : 200.0,
color: selected? Colors.red : Colors.blue,
          alignment:
              selected ? Alignment.center : AlignmentDirectional.topCenter,
          duration: const Duration(seconds: 2),
          curve: Curves.fastOutSlowIn,
          child: const FlutterLogo (size: 75),
        ),
      ),
    );
  }
}

4. Explicit Animation

Implicit animated widgets are simple to use, but there are some disadvantages. Most crucially, the lack of total control over these animations makes it impossible to create recurring animations or to keep an eye on their status and react to modifications.

At that point, explicit animations are helpful. They help the user create complex animations and provide them with total control over the animation process from start to finish.

We can create explicit animation with these two widgets:

Animation Controller, which gives us information about our animation, including its value, status, and other details. It also gives us access to the listener, who is notified when the animation value changes.

Animation Builder, which has three parameters:
1. animation object, which controls the animation;
2. the builder, which recreates the widget whose values are altered
3. For performance reasons, it is possible to supply a child as a parameter that is independent of the animation and isn’t rebuilt each time the value changes.

Here are some other examples of explicit animation widgets:

FadeTransition
RotationTransition
PositionedTransition
ScaleTransition
SizeTransition
SlideTransition

Tween Animations:

Tween is shorthand for “in-betweening.” A tween animation specifies the beginning and ending points as well as a timeline and curve that indicate the length and speed of the transition. The framework computes the transition from the beginning to the end.

In Flutter, the Tween animation is the most fundamental and widely used type of animation. It integrates between two values in a predefined amount of time. For example, you could use a Tween animation to gradually fade in a widget or move it from one location to another.

Alignments, colors, integers, and almost anything else you can think of are examples of values that a tween gives users that fall between two values. The widget does not have to get the value straight from the tween. A tween is applied to the animation itself, giving us precise values at the right moments.

Animation Controller

An animation controller is, as its name suggests, a device that lets you manipulate animations—that is, throw, stop, or trigger them. Nevertheless, driving the animation is the controller’s main responsibility. This suggests that the animation will alter its value and return a new value from the Tween based on how it progresses.

You must first create an AnimationController object and give it the start and end values of the Tween object in order to use a Tween animation. You can control the animation’s duration and timing by doing this. The animation controller plays a vital role in Flutter animation.

Create a curve in your animation:

Using curves in your Flutter animations can help them move more naturally and organically.
some pre-built curves in Flutter:
1. Curves.linear
2. Curves.easeIn
3. Curves.easeOut
4. Curves.easeInOut

Modifying the animation:

By chaining animations together, you can create an animation sequence that plays one after the other. AnimationController’s animateTo function can be used to create chains of animations.

Dart
void chainAnimations() async {
await controller.animateTo(0.5, duration: Duration(seconds: 1));
await controller.animateTo(1.0, duration: Duration(seconds: 1));
}

Custom Painter Animation:

You may create intricate animations by animating custom painters using the CustomPainter class and the CustomPaint widget. Together with an animation controller, these create visually arresting and unique animations.

Dart
class CustomAnimatedPainter extends CustomPainter {
 final Animation<double> animation;
 
 CustomAnimatedPainter({required this.animation}) : super(repaint: animation);
 
 @override
 void paint(Canvas canvas, Size size) {
 final paint = Paint()
 color = Colors.blue
 strokeWidth = 4.0
 style = PaintingStyle.stroke;
 
 final angle = 2 * pi * animation.value;
 final path = Path()
 arcTo(Rect.fromLTWH(0, 0, size.width, size.height), 0, angle, true);
 
 canvas.drawPath(path, paint);
 }
 
 @override
 bool shouldRepaint(CustomAnimatedPainter oldDelegate) {
 return oldDelegate.animation.value != animation.value;
 }
 }

Conclusion:

Flutter animations have been covered in this article. Both fundamental and sophisticated animation techniques that support a smooth user experience are discussed. For more information, visit Flutter Animation.

Check Out Flutter Blogs

FAQ:

1. What is Flutter animation?

Flutter animation involves creating dynamic and interactive user experiences within mobile applications using Google’s UI toolkit, Flutter. It encompasses various techniques to enhance visual elements like transitions, movements, and effects.

2.Why are animations important in mobile applications?

Animations play a crucial role in enhancing user experience by making interactions smoother, providing feedback to user actions, and making the app visually appealing. They can guide users through the interface, communicate changes, and create a sense of fluidity and responsiveness.

3.What are the different types of animations in Flutter?

Flutter supports various animation types, including implicit animations, explicit animations, tween animations, and custom painter animations. Each type serves different purposes and offers different levels of control over the animation process.

4. How do implicit animations work in Flutter?

Implicit animations in Flutter are straightforward to implement and typically involve animating widget properties like size, position, opacity, etc. They are often used for simple animations and can be achieved using pre-built animated widgets provided by Flutter, such as AnimatedContainer, AnimatedOpacity, etc.

5. What is the role of Tween animations in Flutter?

Tween animations in Flutter involve transitioning between two values over a specified duration and curve. They are fundamental for creating smooth transitions and effects, such as fading, scaling, or moving widgets. Tween animations are controlled using AnimationController, which manages the animation’s timing and progress.

6. How can I create custom animations in Flutter?

Custom animations in Flutter can be created using the CustomPainter class along with AnimationController. This approach allows developers to define intricate visual effects and transitions by drawing directly onto the canvas. Custom animations offer complete control over the animation process and are ideal for implementing unique design elements.

7. What are some best practices for Flutter animations?

Some best practices for Flutter animations include using appropriate easing curves to create natural motion, optimizing performance by minimizing unnecessary rebuilds, chaining animations to create sequences, and using Flutter’s built-in animation widgets for common use cases. It’s also essential to test animations across different devices and screen sizes to ensure a consistent experience.

8. Where can I find more resources on Flutter animation?

For more information and tutorials on Flutter animation, you can explore official documentation, community forums, blogs, and online courses dedicated to Flutter development. Additionally, experimenting with code samples and studying open-source projects can help deepen your understanding of animation techniques in Flutter.


FOLLOW US ON

Written and reviewed by

Picture of Muhammad Naeem
Muhammad Naeem
Professional Flutter Developer
Scroll to Top