How to use lerp() method in flutter and what are the use cases?

Viewed 7373

I actually came across the lerp function in many of the Flutter animations. I studied about linear interpolation. But I wonder how it's used in flutter and what are its use cases. could anyone explain it?

2 Answers

It linearly interpolates between two values, for example:

var color = Color.lerp(Colors.white, Colors.black, 0.5);
var value = lerpDouble(10, 20, 0.5); // 15

The color here would have a middle value between white and black.

You can also use it to animate color during dragging on tab view.

btn

var unselectedColor = Theme.of(context).unselectedWidgetColor;
var selectedColor = Theme.of(context).primaryColor;

Color color;

bool isSelected = itemIndex == tabController.index;
int currentIndex = tabController.index;

double offset = tabController.offset;

bool dragToRight = offset > 0;

if (dragToRight) {
  if (itemIndex >= currentIndex && itemIndex <= currentIndex + 1) {
    color = isSelected
        ? Color.lerp(selectedColor, unselectedColor, offset)
        : Color.lerp(unselectedColor, selectedColor, offset);
  }
} else {
  if (itemIndex >= currentIndex - 1 && itemIndex <= currentIndex) {
    color = isSelected
        ? Color.lerp(selectedColor, unselectedColor, -offset)
        : Color.lerp(unselectedColor, selectedColor, -offset);
  }
}
Related