This widget is derived from ImplicitilyAnimatedWidget
. This widget animates a property of a Widget to a target value whenever the target value changes.
const TweenAnimationBuilder<T>({ Key key, @required Tween<T> tween, @required Duration duration, Curve curve: Curves.linear, @required ValueWidgetBuilder<T> builder, VoidCallback onEnd, Widget child })
It has three required property. The property Tween
specifies the animation tween. The property duration
must be used to provide the animation duration. And then builder
property which takes a callback.
When animation begins, the builder
callback is called with each value changed, and updates the UI. The builder
callback is called with three parameters. These are context
, currentValue
and child
resepectively. Here is an example:
@override Widget build(BuildContext context) { return TweenAnimationBuilder( tween: Tween<double>(begin: 0, end: targetValue), duration: Duration(seconds: 1), builder: (BuildContext context, double size, Widget child) { return IconButton( iconSize: size, color: Colors.blue, icon: child, onPressed: () { setState(() { targetValue = targetValue == 24.0 ? 48.0 : 24.0; }); }, ); }, child: Icon(Icons.aspect_ratio), ); }
You can provide any type of animation tween you want, like ColorTween
, RectTween
, DecorationTween
, Tween<T>
etc.
When the widget is built for the first time, it animates from begin
to end
. A new animation can be triggered anytime by providing a new tween with a new targetValue
value. When you change the targetValue
dynamically, the animation runs from current animation value to the new targetValue
.
The animation is further customized by providing a curve
and duration
.
A provided onEnd
callback is called whenever an animation completes. Registering an onEnd
callback my be useful to trigger an action (like another animation) at the end of the current animation.
If your builder
function contains a subtree that does not depend on the animation value, it's more efficient to build that subtree once instead of rebuilding it on every animation tick. If you pass the pre-built subtree as the child
parameter, the widget will pass it back to your builder
function so that you can incorporate it into your build.
Using this pre-built child is entirely optional, but can improve performance significantly in some cases and is therefore a good practice.