How do I apply colors to a multi color svg in flutter?

Issue

I am looking for changing colors of an illustration svg in flutter. I tried flutter_svg package but it support applying only one color to the svg and if I do that svg will be displayed as a single color svg, individual colors are lost. Is there any way to change colors at runtime in flutter for a multi color svg?

Solution

Do you mean something like this? I call it SVG colorization.

SVG Colorization App Demo

I’ll try to squeeze the concept into a short summary. In an SVG file, you need to play around with the fill property as it defines the hex color code.

In terms of programming, you would:

  1. Extract the SVG file data as a String variable svgCode.

Illustration of SVG File Data Extraction into String svgCode

  1. Assign the previous hex color code in previousColor & the currently selected hex color code in newColor.

Illustration of hex color code assignment to variables previousColor & newColor

  1. Apply the String.replaceAll method on svgCode to replace the colors.

Illustration of hex color code replacement

  1. Update the value of the previousColor.

Illustration of previousColor value updation

A more brief elaboration would be

/// Initially without any color selection.
SVGPicture.string('''<svg code with fill #f7ebcb>''');
/// After the user selects the red color.
SVGPicture.string('''<svg code with fill #FF0000>''');

This tutorial can help to solve your issue. Not only does this app changes the color on runtime, but it also allows the user to download the manipulated SVG code.

Answered By – Zujaj Misbah Khan

Answer Checked By – Cary Denson (FlutterFixes Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *