Sub topic 6
Custom implicit animations with TweenAnimationBuilder
This chapter assumes you can write a StatefulWidget with setState, you know what a builder callback is, and you have used AnimatedContainer with a duration and a curve. You do not need AnimationController yet. That comes later.
Why a builder-based implicit widget exists
AnimatedContainer, AnimatedOpacity and the other built-in implicit widgets each animate a fixed set of properties. If you want to animate something they don't cover, such as a rotation angle, a blur radius, a gradient stop or a number shown in a label, none of them fits.
TweenAnimationBuilder<T> fills that gap. You give it a Tween<T>, a duration and a builder. Flutter animates the value from the tween's start to its end and calls your builder on each frame. You still don't create, start or dispose a controller. The widget owns one internally.
| Parameter | Required | Purpose |
|---|---|---|
| `tween` | yes | Describes the start and end values and how to interpolate between them |
| `duration` | yes | How long one animation takes |
| `builder` | yes | Builds the subtree from the current value |
| `curve` | no | Shapes the progress over time. Defaults to `Curves.linear` |
| `onEnd` | no | Called when an animation finishes |
| `child` | no | A subtree that does not depend on the value, passed back to the builder unchanged |
The first run and later changes
The widget treats the tween differently on its first build and on later rebuilds.
- On the first build, it animates from
tween.begintotween.end. - On a later rebuild, if
tween.endhas changed, it starts a new animation from the value it is currently showing to the new end. The newbeginis ignored. - If
tween.endhas not changed, nothing happens, even ifbeginchanged.
Because of the second rule, a change of target in the middle of an animation does not jump. The motion continues smoothly from wherever it was.
Example: a rotating icon
This widget animates to whatever turns value its parent passes. One turn is a full rotation.
import 'dart:math' as math;
import 'package:flutter/material.dart';
class RotatingIcon extends StatelessWidget {
const RotatingIcon({super.key, required this.turns});
final double turns;
@override
Widget build(BuildContext context) {
return TweenAnimationBuilder<double>(
tween: Tween<double>(begin: 0, end: turns),
duration: const Duration(milliseconds: 500),
curve: Curves.easeOut,
builder: (context, value, child) {
return Transform.rotate(angle: value * 2 * math.pi, child: child);
},
child: const Icon(Icons.refresh, size: 48),
);
}
}RotatingIcon is a StatelessWidget. The animation state lives inside TweenAnimationBuilder, so the parent only supplies the target. If the parent changes turns from 0 to 1, the icon spins one full turn. If it then changes to 3 while the icon is halfway, the icon continues from its current angle toward three turns over a fresh 500 ms.
To see it run, put it under a stateful parent:
import 'package:flutter/material.dart';
void main() => runApp(const MaterialApp(home: RotationDemo()));
class RotationDemo extends StatefulWidget {
const RotationDemo({super.key});
@override
State<RotationDemo> createState() => _RotationDemoState();
}
class _RotationDemoState extends State<RotationDemo> {
double _turns = 0;
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(child: RotatingIcon(turns: _turns)),
floatingActionButton: FloatingActionButton(
onPressed: () => setState(() => _turns += 0.25),
child: const Icon(Icons.add),
),
);
}
}Add the RotatingIcon class from the previous listing to the same file. Each tap adds a quarter turn, and tapping quickly shows the "continue from the current value" behavior.
The child parameter
The builder runs on every frame, so anything it creates is rebuilt about 60 times a second. In RotatingIcon, the Icon does not depend on the animated value, so it is passed as child. The builder receives the same instance each time and wraps it in Transform.rotate. Only the cheap wrapper is rebuilt.
Use child for any expensive subtree that stays the same during the animation, such as an image, a list or a large text block.
Tweens for other types
Tween<T> works for any type that supports +, - and *, which covers double, Offset, Size and similar. Other types need their own tween class. These are the common ones:
ColorTweenforColor?SizeTweenandRectTweenforSize?andRect?AlignmentTween,BorderRadiusTweenandEdgeInsetsTweenfor the matching layout typesIntTweenfor integers, which rounds the interpolated value
Note the nullable type arguments. ColorTween is a Tween<Color?>, so the builder receives a Color?.
import 'package:flutter/material.dart';
class TintedHeart extends StatelessWidget {
const TintedHeart({super.key, required this.liked});
final bool liked;
@override
Widget build(BuildContext context) {
return TweenAnimationBuilder<Color?>(
tween: ColorTween(
begin: Colors.grey,
end: liked ? Colors.red : Colors.grey,
),
duration: const Duration(milliseconds: 300),
builder: (context, color, child) {
return Icon(Icons.favorite, size: 48, color: color);
},
);
}
}The first build shows grey with no animation, because begin and end are equal. When liked becomes true, the end changes to red and the color fades from grey to red. When liked goes back to false, the end returns to grey and it fades back from wherever it was.
Animating once on appearance
Sometimes you want an animation that runs when the widget first appears, with no state change. Use a constant tween such as Tween<double>(begin: 0, end: 1). On the first build it animates from 0 to 1, and because end never changes afterward, it never runs again.
import 'package:flutter/material.dart';
class FadeInOnce extends StatelessWidget {
const FadeInOnce({super.key, required this.child});
final Widget child;
@override
Widget build(BuildContext context) {
return TweenAnimationBuilder<double>(
tween: Tween<double>(begin: 0, end: 1),
duration: const Duration(milliseconds: 600),
curve: Curves.easeIn,
builder: (context, value, child) {
return Opacity(
opacity: value,
child: Transform.translate(
offset: Offset(0, (1 - value) * 20),
child: child,
),
);
},
child: child,
);
}
}Common errors
- Changing only
begin. Nothing animates. Only a change ofendstarts an animation. - Expecting a restart on the same target. Setting
endto the value it already has does nothing. If you need to replay an animation, you need a controller, or you can give the widget a newKeyso Flutter builds a fresh one. - Wrong tween type.
Tween<Color>throws at runtime becauseColordoes not support the arithmetic operatorsTweenuses. UseColorTween. - Forgetting the nullable type.
TweenAnimationBuilder<Color>with aColorTweengives a type error, since the tween isTween<Color?>. - Heavy work in the builder. Move static subtrees into
child. - Treating
onEndas a loop. It fires once each time an animation finishes. CallingsetStatein it to flip the target creates a back-and-forth effect, but it is fragile. If you need looping, use an explicit animation.
Key points
TweenAnimationBuilderanimates any value you can describe with aTweenand gives you a builder to use it.- A changed
endstarts a new animation from the current value. A changedbeginis ignored after the first build. - Pass static subtrees as
childso they are not rebuilt each frame. - It has no controller, so it cannot reverse, repeat or be paused.
Exercise
A parent widget rebuilds a TweenAnimationBuilder<double> every second. It always passes Tween<double>(begin: 0, end: 5), so the end never changes. Midway through the first animation, the parent changes the tween to Tween<double>(begin: 2, end: 5). What happens to the animation, and what must change for the animation to head somewhere new?
Show answer
Nothing visible happens. The end is still 5, so the widget keeps the running animation and ignores the new begin of 2. The animation continues toward 5 from its current value. To send it somewhere new, the parent must pass a different end value, for example Tween<double>(begin: 0, end: 8). The widget would then animate from its current value to 8.
Exercise
Write a TweenAnimationBuilder<double> that smoothly changes the width of a blue Container to a target width passed in from the parent, over 250 ms with Curves.easeInOut. Which parameter would you use so that a static Text inside the Container is not rebuilt on every frame?
Show answer
Use tween: Tween<double>(begin: 0, end: targetWidth) (or begin: targetWidth to avoid the initial grow), duration: const Duration(milliseconds: 250), curve: Curves.easeInOut, and a builder such as (context, value, child) => Container(width: value, color: Colors.blue, child: child). Pass the Text as the child parameter of TweenAnimationBuilder so the builder reuses the same instance on each frame.