Flutter/Dart : How to get single colors from Colorgradient?

332

Ok I actually found two Solutions:

1. Use Color.lerp(color a, color b, double p) function What this does is it creates a gradient between a and b, and return the color that exist on point p (value between 0 and 1) on that scale. This is basically what I wanted, but there is a problem: It doesn't necessarily interpolate those two color with colors that you want to be inbetween, it's more of a brown-ish mix between those two.

2. Install the rainbow_color package This was exactly what I needed, you can insert multiple custom colors, specify a range of values that you use (in my case 0.0 and 1.0, but it can also be integers), and it returns a gradient between only theese colors:

  var rb = Rainbow(
    spectrum: [
      Color(0xff1fff00),
      Color(0xffd0ff00),
      Color(0xffffaa00),
      Color(0xffffaa00),
      Color(0xffff6600)
    ],
    rangeStart: 1.0,
    rangeEnd: 0.0
  );

  return rb[remainingFraction];

enter image description here

Share:
332
Washbear
Author by

Washbear

Updated on December 28, 2022

Comments

  • Washbear
    Washbear over 1 year

    I am trying to build a Widget that changes it's background color from green to red over time, but in a fluid way. So similar to a gradient background:

    enter image description here

    But not as a fixed gradient, but rather a full green background at the beginning, and as the time counts down the background should slowly transition over to yellow, then orange, then red at the end.

    I want the color to update every 10 miliseconds so it's not an abrupt change. I am handling the changing with a timer which calculates how much time has passed in relation to the start time and update the color accordingly.

    Now - is there any way how I can get A concrete color from a gradient-like object? Like I could just extract the color of a gradient at a specific point (which is the fraction of time_passed/max_time) to use it as the full background? Or should I actually use Colorcodes and just increase the value of the colorcode every 10ms? That seems not very graceful

  • Randal Schwartz
    Randal Schwartz about 3 years
    If you're gonna lerp colors, it's better to use HSVColor() objects (easily mapped to and from Color() objects) because they provide a more natural lerping.