Sub topic 6
Custom implicit animations with TweenAnimationBuilder
Prerequisites and the working model
Assume you know Dart classes, generics, closures, StatefulWidget, and setState. You should also understand that Flutter rebuilds widgets when state changes.
TweenAnimationBuilder<T> is an implicit animation widget for values that are not covered by a specialized widget such as AnimatedContainer. It receives a Tween<T>, which describes a value range, and gradually changes the value from the old result to the new end value.
The builder callback receives the current animated value on every frame. Use that value to build the widget that should change.
Animate a custom value
This example rotates an icon by a number of turns. The parent can pass a new turns value whenever it wants the icon to rotate farther.
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),
);
}
}Tween<double> produces values between its begin and end. A value of 1.0 means one full turn, so the example converts turns to radians by multiplying by 2 * math.pi.
When the parent supplies a different turns value, Flutter animates from the current value to the new end value. The animation does not require a controller, a ticker, or a dispose method.
Keep static children outside the builder
The child parameter is useful for widgets that do not change during the animation. Flutter builds the icon once and passes it to the callback. The callback only rebuilds Transform.rotate.
Without child, placing the icon inside the builder would rebuild that subtree on every animation frame. That may be harmless for a small icon, but separating static content is a useful habit for larger widgets.
When to use it
Use TweenAnimationBuilder when:
- one or more values should animate toward a new target;
- the widget does not need direct playback control;
- you want a custom type or property that built-in animated widgets do not expose.
Choose an explicit AnimationController when you need to pause, reverse, repeat, coordinate several playback phases, or react to animation status.
Exercise
What does the value argument in the builder represent?
Show answer
It is the interpolated value for the current animation frame, between the tween's start and end values.