Ask Your Question

Revision history [back]

Gradient colors can be added to SVG icons in Flutter by using the svg package and the PathPiece class. This class allows us to apply a gradient to the SVG paths.

First, we need to import the svg package:

import 'package:flutter_svg/flutter_svg.dart';

Then, we can load the SVG asset and create a PathPiece object from the SVG path:

final icon = SvgPicture.asset(
  'assets/icons/my_icon.svg',
  width: 24,
  height: 24,
);

final pathPiece = PathPiece.parsePath(icon.pictureProvider.string);

Next, we can create a Paint object and set its shader to a LinearGradient:

final gradient = LinearGradient(
  colors: [Colors.red, Colors.blue],
  begin: Alignment.topLeft,
  end: Alignment.bottomRight,
);

final paint = Paint()
  ..shader = gradient.createShader(pathPiece.getBounds());

Finally, we can draw the SVG path with the gradient fill:

Canvas canvas = ...; // get canvas from Paint widget or other

canvas.drawPath(
  pathPiece.path,
  paint,
);