What is the Tween animation in Flutter?

Tween animation in Flutter includes creating an intermediate state between the two endpoints, a starting state and an ending state. If you are moving a widget from point A to point B, you can use the Tween animation for a smoother transition between two states.

Note: Tween is short for “in-between” and is used to refer to the frames that exist in between keyframes. These frames help to create an illusion of transition between the two end states.

How to define a Tween

Tween is a stateless object which generates a set of new values based on the specified start point, end point, and a cycle duration.

Given below is the syntax of defining a Tween.

// Declaration of Tween
Tween doubleTween = Tween<double>(begin: 0, end: 10);
// Use of Tweendouble
value = doubleTween.transform(0.5);

Here,

  • Line 1: doubleTween is a Tween object which represents the values ranging from 0 to 10.

  • Line 5: The transform() method is called with the value set to 0.5. It determines the time period of one animation cycle.

Note: 

  • The greater the duration value, the longer the animation will take to complete one cycle.

  • The smaller the value, the faster the animation will complete one cycle.

  • Moreover, 0.5 is not the value to which the points are incremented. It is the time period for one cycle completion.

Types of Tween

Tween animation is mainly used with AnimationController, which helps play the animations forward or backward. AnimationController takes the duration value which determines the period to complete one animation cycle.

Flutter supports many types of Tween animations such as  SizeTween, ColorTween, and RectTween.

Code

Here is the code which combines all the three types of Tween animations namely SizeTweenColorTween, and RectTween.

import 'package:flutter/material.dart';
void main()
{
  runApp(MyApp());
}
class MyApp extends StatelessWidget
{
  @override
  Widget build(BuildContext context)
  {
    return MaterialApp(home: Scaffold(body: TweenAnimation(),),);
  }
}
class TweenAnimation extends StatefulWidget
{
  @override
  TweenAnimationState createState() => TweenAnimationState();
}
class TweenAnimationState extends State<TweenAnimation> with SingleTickerProviderStateMixin
{
  AnimationController controller;
  Animation sizeAnimation;
  Animation<Color> colorAnimation;
  Animation<Rect> rectAnimation;
  
  @override
  void initState()
  {
    super.initState();
    controller = AnimationController(duration: const Duration(seconds: 5), vsync: this,)..repeat();
    sizeAnimation = Tween(begin: 100.0, end: 10.0,).animate(controller);
    colorAnimation = ColorTween(begin: Colors.red, end: Colors.purple,).animate(controller);
    rectAnimation = RectTween(begin: Rect.fromLTWH(0, 0, 100, 100), end: Rect.fromLTWH(450, 200, 10, 10),).animate(controller);
  }
  @override
  Widget build(BuildContext context)
  {
    return Stack(
      children:
      [
        AnimatedBuilder(animation: controller,builder: (context, child)
        {
          return Positioned.fromRect(rect: rectAnimation.value, child: Container(width: sizeAnimation.value, height: sizeAnimation.value, color: colorAnimation.value,),);
        },),
      ],);
  }
  @override
  void dispose()
  {
    controller.dispose();
    super.dispose();
  }
}
SizeTween, ColorTween, and RectTween animation

Explanation

  • Lines 4: runApp() makes the Widget the root of the widget treeA tree that holds all your widgets within each other. It is how you structure your User Interface (UI)..

  • Lines 6–13: A new class named MyApp is defined which extends the statelessWidget class. MaterialApp provides features such as Scaffold (A basic layout to design applications), a Center widget (to center the child widgets), and a TweenAnimation().

  • Line 17: createState() method creates an instance of the class named TweenAnimationState.

  • Line 19: The state class TweenAnimationState extends the TweenAnimation class which is created by SingleTickerProviderStateMixin. It is a mixin which is used to create Ticker to control animations.

  • Lines 21 & 30: An instance variable Controller is declared and initialized to the duration of 2 seconds. So, the total time period for the animation to complete is 2 seconds. vsync.this makes the animationController synchronized.

    • It is used to inform controller about the screen updates to play animations accordingly. ..repeat(reverse: true) reverses the direction after the completion of each animation cycle. It causes the animation to repeat infinitely.

  • Lines 22 & 31: sizeAnimation is declared and initialized to control the size of the object and it has a value of double. The square will change its size from 100 to 10 during each animation cycle.

  • Lines 23 & 32: colorAnimation is being declared and initialized here. It has the start state of red color and an end state of purple color. The square changes its color from red to purple within the completion of each duration cycle. The animate() method is called to play the ColorTween animation.

  • Lines 24 & 33: rectAnimation is being declared here which is used for interpolationGenerating a series of rectangles that changes state from first rectangle to the second rectangle. between two rectangles. It takes the begin and end of the two rect objects.

    • fromLTWH() takes as parameters, the starting position which is set to left = 0, right = 0, width = 100 and height = 100.

    • The ending position is set to left = 450, right = 200, width = 100 and height = 100. The animate() is called to play the rectTween animation.

  • Line 29: initState() is called only once to initialize the state.

  • Line 36: build is a method in the state class. It takes the object BuildContext and returns a Stack widget. It contains AnimatedBuilder which is a widget that rebuilds itself each time the controller is called (when the state of the animation changes).

  • Lines 41–43: AnimatedBuilder returns a positioning widget called the Positioned.

    • fromRect() method sets the left, right, width, and height to the current value of rectAnimation.

    • The width and height of the square is set to the values being initialized in line 35.

    • The color of the square is set to the value which is being initialized in line 36.

    • As result, the square will change its position from one place to the other based on the defined coordinates.

  • Lines 48–51: dispose() method is used to prevent any memory leaks. It cleans up the Controller whenever the state object is removed.

Learn more about Flutter

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved