applyLinear method

Gradient applyLinear({
  1. required List<Color> colors,
  2. double? angle,
  3. LinearGradientDirection? direction,
  4. List<Dim>? stops,
})

Adds a linear gradient.

If both angle and direction are provided, angle takes precedence.

Example

final gradient = Gradient()
  ..applyLinear(
    colors: const [Color('#3b82f6'), Colors.purple],
    direction: LinearGradientDirection.toRight,
    stops: const [Dim.px(20), Dim.percent(80)],
    angle: 90,
  );
  • colors: List of stop colors (minimum of 2 recommended).
  • angle: Angle of the gradient. It will be normalized to be within the 1-360 range (e.g., 400° becomes 40°, -10° becomes 350°).
  • direction: Linear gradient direction.
  • stops: Optional stops corresponding to colors. Accepts length or percentage units (e.g., Dim.percent(50), Dim.px(20), Dim.rem(1.5)). Unitless numbers are not valid CSS.

Implementation

Gradient applyLinear({
  required List<Color> colors,
  double? angle,
  LinearGradientDirection? direction,
  List<Dim>? stops,
}) {
  final List<String> parts = [];

  if (angle != null) {
    angle = angle % 360;
    parts.add('${angle}deg');
  } else if (direction != null) {
    parts.add(direction.value);
  }

  for (int i = 0; i < colors.length; i++) {
    final colorStr = colors[i].value;

    if (stops != null && i < stops.length) {
      parts.add('$colorStr ${stops[i]}');
    } else {
      parts.add(colorStr);
    }
  }

  _gradients.add(GradientType.linear.cssText(parts));

  return this;
}