Animating HSV colors with TweenAnimationBuilder

Playground

You can code along with this lesson with this example on Dartpad:

Notes

To make things more interesting, the end argument of the Tween value passed to TweenAnimationBuilder can be animated.

TweenAnimationBuilder<double>(
  tween: Tween<double>(begin: 0.0, end: _hue),
  duration: Duration(milliseconds: 1500),
  builder: (context, hue, child) {
    final hsvColor = HSVColor.fromAHSV(1.0, hue, 1.0, 1.0);
    return Container(
      width: 200,
      height: 200,
      color: hsvColor.toColor(),
    );
  },
)

In this example we do this in response to an input event such as the user dragging the value of a slider that controls the hue component.

Slider.adaptive(
  value: _hue,
  min: 0,
  max: 360,
  onChanged: (newHue) => setState(() => _hue = newHue),
)

Additional notes

Flutter already knows how to interpolate values of the most common types (doubleOffsetColor).

If you want to use TweenAnimationBuilder and interpolate your own types, you need to provide an interpolation function called lerp() which stands for "linear interpolation".

Here's how lerp() is implemented in the Color class:

You can use this as reference if you want to implement your own.

Performance optimizations with TweenAnimationBuilder

When you work with TweenAnimationBuilder, you can improve the performance of your code by using the child argument.

This article explain why this is important and covers all the details:

Discussion

2 comments