Sub topic 11
Mapping values with Tween
An AnimationController produces numbers from 0.0 to 1.0. Widgets need other kinds of values, such as widths in pixels, colors, offsets, and rectangles. A Tween converts one into the other. This chapter covers how tweens work, which ones ship with Flutter, how to chain them with curves, and the mistakes that cause trouble.
You should already know how to create and dispose an AnimationController with a TickerProviderStateMixin, and how AnimatedBuilder rebuilds a subtree. Dart generics are also assumed.
What a Tween is
Tween<T> is short for "in-betweening". It has a begin and an end of type T. It also extends Animatable<T>, which is an object that can turn a double into a T.
A tween is not an animation. It has no clock, no listeners, and no status. It is a stateless mapping, a function from t to T. Its core method is transform(double t). For t equal to 0 or 1 it returns begin or end directly. For any other value it calls lerp(t).
For the default lerp, Dart evaluates begin + (end - begin) * t. That only compiles at runtime if T supports +, -, and * by a double. double, Offset, Size, and EdgeInsets support all three. Color does not, so Flutter provides ColorTween, which overrides lerp.
import 'package:flutter/animation.dart';
void main() {
final width = Tween<double>(begin: 100, end: 300);
print(width.transform(0.0)); // 100.0
print(width.transform(0.25)); // 150.0
print(width.transform(1.0)); // 300.0
}Connecting a tween to a controller
There are three equivalent ways to combine a tween with an animation.
tween.animate(parent)returns anAnimation<T>whose value istween.evaluate(parent).parent.drive(tween)does the same thing, read left to right.tween.evaluate(animation)computes a one-off value inside a builder, with no newAnimationobject.
The Animation returned by animate is a thin wrapper. It forwards status changes and listeners from the parent and calls the tween each time you read .value. Create it once, in initState, rather than inside build. Otherwise every rebuild allocates a new object.
Built-in tween types
| Class | Value type | Notes |
|---|---|---|
| `Tween<double>` | `double` | The most common tween. |
| `IntTween` | `int` | Rounds the interpolated result. |
| `ColorTween` | `Color?` | Uses `Color.lerp`. The result is nullable. |
| `SizeTween` | `Size?` | Interpolates width and height. |
| `RectTween` | `Rect?` | Often used for hero-style transitions. |
| `AlignmentTween` | `Alignment` | Used with `Align` and `AlignTransition`. |
| `BorderRadiusTween` | `BorderRadius?` | Interpolates corner radii. |
| `CurveTween` | `double` | Applies a curve. Chain it before another tween. |
| `ConstantTween<T>` | `T` | Always returns one value. |
| `TweenSequence<T>` | `T` | Joins several tweens, each with a weight. |
Several of these produce nullable types, such as Animation<Color?>. Widgets that take a non-null color need value! or a fallback.
A complete example
This widget toggles on tap. It animates width and color from one controller. A CurveTween is chained before each tween to shape the motion.
import 'package:flutter/material.dart';
class TweenDemo extends StatefulWidget {
const TweenDemo({super.key});
@override
State<TweenDemo> createState() => _TweenDemoState();
}
class _TweenDemoState extends State<TweenDemo>
with SingleTickerProviderStateMixin {
late final AnimationController _controller;
late final Animation<double> _width;
late final Animation<Color?> _color;
bool _expanded = false;
@override
void initState() {
super.initState();
_controller = AnimationController(
vsync: this,
duration: const Duration(milliseconds: 600),
);
final eased = _controller.drive(CurveTween(curve: Curves.easeInOut));
_width = eased.drive(Tween<double>(begin: 80, end: 240));
_color = eased.drive(ColorTween(begin: Colors.orange, end: Colors.teal));
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
void _toggle() {
_expanded = !_expanded;
_expanded ? _controller.forward() : _controller.reverse();
}
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: _toggle,
child: AnimatedBuilder(
animation: _controller,
builder: (context, child) {
return Container(
width: _width.value,
height: 60,
color: _color.value,
);
},
),
);
}
}The builder listens to _controller. _width and _color are derived from it, so one listener covers both. Because the tweens are stateless, the same code works in reverse. Calling reverse() makes t fall from 1 to 0, and the tweens map it back.
Chaining and curves
Animatable.chain(parent) composes two animatables into one. In a.chain(b), the result is a evaluated at b's output. So Tween<double>(begin: 80, end: 240).chain(CurveTween(curve: Curves.easeIn)) evaluates the curve first and then the tween. Confusingly, drive reads left to right, but chain reads inside out. Prefer drive unless you need a reusable Animatable.
CurvedAnimation and CurveTween do the same job. CurvedAnimation wraps an animation and has its own reverseCurve. CurveTween is stateless and can be shared by several animations. Use CurvedAnimation when forward and reverse need different curves.
Custom tweens
Subclass Tween<T> and override lerp when T lacks the arithmetic operators.
import 'package:flutter/animation.dart';
class Point {
const Point(this.x, this.y);
final double x;
final double y;
}
class PointTween extends Tween<Point> {
PointTween({super.begin, super.end});
@override
Point lerp(double t) => Point(
begin!.x + (end!.x - begin!.x) * t,
begin!.y + (end!.y - begin!.y) * t,
);
}The begin! and end! assertions are deliberate. A tween with a null endpoint throws when evaluated, and that is usually the right failure.
Multi-step motion with TweenSequence
TweenSequence splits the 0 to 1 range into weighted segments. Each segment runs its own tween. This builds a "grow, then shrink" effect from one controller.
final scale = TweenSequence<double>([
TweenSequenceItem(tween: Tween(begin: 1.0, end: 1.4), weight: 30),
TweenSequenceItem(tween: Tween(begin: 1.4, end: 1.0), weight: 70),
]).animate(controller);The weights are relative, so 30 and 70 give 30% and 70% of the duration. Adjacent segments should meet at the same value, or the output jumps.
Common errors
- Mutating a shared tween.
beginandendare mutable. Changing them while an animation runs makes the value jump on the next tick. Make a new tween and animation instead. - Curves that overshoot. Curves such as
Curves.elasticOutandCurves.easeOutBackreturn values below 0 or above 1. The tween extrapolates, which is what you want for width, butOpacityasserts that its value is between 0 and 1. Clamp the value, or use a curve that stays in range for opacity. - Wrong generic type.
Tween(begin: 0, end: 1)infersTween<int>. UseTween<double>or write0.0and1.0, oranimatereturns the wrong type. - Using
Tween<Color>. It throws at runtime becauseColorhas no-operator. UseColorTween. - Forgetting nullability.
ColorTweengivesColor?. Passing_color.valuestraight to a property that needs a non-nullColorfails at compile time. - Building animations in
build. Callinganimatethere creates new objects on every frame the parent rebuilds.
Exercise
A widget needs an IntTween from 0 to 100 driven by a controller whose curve is Curves.easeOut. In what order do the curve and the tween run, and which form of drive would you write?
Show answer
The curve runs first. It reshapes the controller's t, and the tween maps the reshaped value to an int. Write controller.drive(CurveTween(curve: Curves.easeOut)).drive(IntTween(begin: 0, end: 100)).
Exercise
You write Tween<Color>(begin: Colors.red, end: Colors.blue).animate(controller). What goes wrong, and what is the fix?
Show answer
Color does not support the - and * operators that the default lerp uses, so the tween throws when it is evaluated. Use ColorTween, which calls Color.lerp and gives an Animation<Color?>.