sample method Null safety

Color sample(
  1. List<Color> colors,
  2. List<double> stops,
  3. double t
)

Calculate the color at position t of the gradient defined by colors and stops.
Modified from vanilla Gradient _sample() to support fewer Colors.

This abstracts the color selection process from the gradient type itself.

Implementation

// // static Color sample(List<Color> colors, List<double> stops, double t, bool isDecal ) {
static Color sample(List<Color> colors, List<double> stops, double t) {
  if (colors.isEmpty) {
    colors = [Colors.transparent, Colors.transparent];
  } else if (colors.length == 1) {
    colors = colors + colors;
  }
  if (stops.isEmpty) {
    stops = [0.0, 1.0];
  } else if (stops.length == 1) {
    if (!stops.contains(1.0)) {
      stops = stops + [1.0];
    } else {
      stops = [0.0] + stops;
    }
  }
  final safeLength = math.min(colors.length, stops.length);
  final safeColors = <Color>[for (int i = 0; i < safeLength; i++) colors[i]];
  //final safeStops = <double>[for (int i = 0; i < safeLength; i++) stops[i]];
  for (var i = safeLength; i < stops.length; i++) {
    safeColors.add(colors.last);
  }
  // Colors at beginning and ending of stops/gradient
  if (t <= stops.first) {
    return // isDecal ? colors.first.withOpacity(0.0) :
        colors.first;
  }
  if (t >= stops.last) {
    return // isDecal ? colors.last.withOpacity(0.0) :
        colors.last;
  }
  final index = stops.lastIndexWhere((double s) => s <= t);
  return Color.lerp(
    safeColors[index],
    safeColors[index + 1],
    (t - stops[index]) / (stops[index + 1] - stops[index]),
  )!;
}