Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

flutter

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?

like image 259
Bala Ganesh Avatar asked May 19 '20 11:05

Bala Ganesh


People also ask

What is lerp in Flutter?

lerp method Null safetyLinearly interpolate between two LinearGradients. If either gradient is null, this function linearly interpolates from a a gradient that matches the other gradient in begin, end, stops and tileMode and with the same colors but transparent (using scale).

What is lerp method?

lerp method Null safetyLinearly interpolate between two colors. This is intended to be fast but as a result may be ugly. Consider HSVColor or writing custom logic for interpolating colors. If either color is null, this function linearly interpolates from a transparent instance of the other color.


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.

like image 180
iDecode Avatar answered Oct 05 '22 13:10

iDecode


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);
  }
}
like image 30
Thea Choem Avatar answered Oct 05 '22 14:10

Thea Choem