createShimmerShader function

Shader createShimmerShader({
  1. required Rect bounds,
  2. required double progress,
  3. required Color baseColor,
  4. required Color highlightColor,
  5. required ShimmerDirection direction,
})

Helper creating a sweeping LinearGradient shader across bounds.

Implementation

Shader createShimmerShader({
  required Rect bounds,
  required double progress,
  required Color baseColor,
  required Color highlightColor,
  required ShimmerDirection direction,
}) {
  Alignment begin;
  Alignment end;

  // Linear translation offset from -1.0 to 2.0 to ensure complete traversal
  final double dx = (progress * 3.0) - 1.0;

  switch (direction) {
    case ShimmerDirection.ltr:
      begin = Alignment(dx - 1.0, 0.0);
      end = Alignment(dx + 1.0, 0.0);
      break;
    case ShimmerDirection.rtl:
      final double rdx = (1.0 - progress) * 3.0 - 1.0;
      begin = Alignment(rdx + 1.0, 0.0);
      end = Alignment(rdx - 1.0, 0.0);
      break;
    case ShimmerDirection.ttb:
      begin = Alignment(0.0, dx - 1.0);
      end = Alignment(0.0, dx + 1.0);
      break;
    case ShimmerDirection.btt:
      final double rdy = (1.0 - progress) * 3.0 - 1.0;
      begin = Alignment(0.0, rdy + 1.0);
      end = Alignment(0.0, rdy - 1.0);
      break;
    case ShimmerDirection.auto:
      begin = Alignment(dx - 1.0, 0.0);
      end = Alignment(dx + 1.0, 0.0);
      break;
  }

  return LinearGradient(
    begin: begin,
    end: end,
    colors: [baseColor, highlightColor, baseColor],
    stops: const [0.0, 0.5, 1.0],
  ).createShader(bounds);
}