tezvyn:

Flutter's Tween: The Recipe for Animation

AI-drafted, machine-checkedSource: api.flutter.devintermediate

A Tween is a recipe for animation, not the animation itself. It maps a 0.0-1.0 progress value to a concrete value, like a color or position. Use it with an AnimationController to smoothly transition a widget's properties.

WHY IT EXISTS: Flutter needs a way to calculate intermediate values for animations. An AnimationController just provides a ticking number from 0.0 to 1.0. A Tween bridges the gap between that abstract progress and the concrete property values (like colors, sizes, or positions) you want to animate.

THE MENTAL MODEL: Think of a Tween as a stateless mapping function, not a running animation. It's a recipe that says: "Given a progress value 't' between 0.0 and 1.0, here's how to calculate the corresponding value between my 'begin' and 'end' points." The AnimationController provides the 't', and the Tween does the math.

HOW IT WORKS: You create a Tween with begin and end values, for example, Tween<double>(begin: 0, end: 200). You then connect this to an AnimationController by calling myTween.animate(myController). This creates an Animation object. As the controller's value goes from 0.0 to 1.0, the Animation object's .value will go from 0 to 200. The core logic is the lerp (linear interpolation) method, which calculates begin + (end - begin) * t.

WHEN TO USE IT: Use a Tween whenever you need to animate a property between two specific values. This is the most common way to create animations in Flutter for fading (ColorTween), resizing (SizeTween), moving (Tween<Offset>), and more. For constant animations, declare the Tween as a static final variable to avoid recreating it in build methods, which improves performance.

WHEN NOT TO USE IT: A Tween is for interpolating between two known points. If your animation logic is more complex and doesn't follow a simple begin-to-end path (e.g., it's based on physics), you might use a PhysicsBased simulation instead. A Tween itself also doesn't manage state or lifecycle; you always need a controller like AnimationController to drive it.

ONE CANONICAL EXAMPLE: To animate a widget's opacity from transparent to opaque, you'd use an AnimationController and a Tween. First, define the controller: _controller = AnimationController(vsync: this, duration: Duration(milliseconds: 500)). Then, define the tween: _opacityTween = Tween<double>(begin: 0.0, end: 1.0). Finally, connect them to create the animation: _opacityAnimation = _opacityTween.animate(_controller). In your build method, you would use this animation's value to set the opacity.

Read the original → api.flutter.dev

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.