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:
Tweenis 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 TweenTween doubleTween = Tween<double>(begin: 0, end: 10);// Use of Tweendoublevalue = doubleTween.transform(0.5);
Here,
Line 1:
doubleTweenis aTweenobject which represents the values ranging from0to10.Line 5: The
transform()method is called with the value set to0.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.5is 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 SizeTween, ColorTween, 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();
}
}Explanation
Lines 4:
runApp()makes theWidgetthe root of the .widget tree A 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
MyAppis defined which extends thestatelessWidgetclass.MaterialAppprovides features such asScaffold(A basic layout to design applications), aCenterwidget (to center the child widgets), and aTweenAnimation().Line 17:
createState()method creates an instance of the class namedTweenAnimationState.Line 19: The state class
TweenAnimationStateextends theTweenAnimationclass which is created bySingleTickerProviderStateMixin. It is a mixin which is used to createTickerto control animations.Lines 21 & 30: An instance variable
Controlleris declared and initialized to thedurationof2seconds. So, the total time period for the animation to complete is2seconds.vsync.thismakes theanimationControllersynchronized.It is used to inform
controllerabout 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:
sizeAnimationis declared and initialized to control the size of the object and it has a value ofdouble. The square will change its size from100to10during each animation cycle.Lines 23 & 32:
colorAnimationis being declared and initialized here. It has the start state ofredcolor and an end state ofpurplecolor. The square changes its color fromredtopurplewithin the completion of eachdurationcycle. Theanimate()method is called to play theColorTweenanimation.Lines 24 & 33:
rectAnimationis being declared here which is used for between two rectangles. It takes theinterpolation Generating a series of rectangles that changes state from first rectangle to the second rectangle. beginandendof the tworectobjects.fromLTWH()takes as parameters, the starting position which is set to left =0, right =0, width =100and height =100.The ending position is set to left =
450, right =200, width =100and height =100. Theanimate()is called to play therectTweenanimation.
Line 29:
initState()is called only once to initialize the state.Line 36:
buildis a method in thestateclass. It takes the objectBuildContextand returns aStackwidget. It containsAnimatedBuilderwhich is a widget that rebuilds itself each time thecontrolleris called (when the state of the animation changes).Lines 41–43:
AnimatedBuilderreturns a positioning widget called thePositioned.fromRect()method sets the left, right, width, and height to the current value ofrectAnimation.The width and height of the square is set to the values being initialized in line 35.
The
colorof 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 theControllerwhenever thestateobject is removed.
Learn more about Flutter
Free Resources