Flutter performance tip: How to use SVG assets as a pro developer
As a Flutter developer, you’ve likely used SVG assets in your Flutter application with the flutter_svg
package. You’ve probably encountered an issue where the app loads, but your SVG is rendered late.
To tackle this issue, you can pre-cache your assets before loading the application. However, there’s another approach: you can use SVG in your application without any package.
By adding SVG to your assets and avoiding late render issues, the method I’m going to share with you can also enhance your app’s performance.
- For example, if you have an SVG, simply navigate to the Flutter Shape Maker. There, you will encounter an interface like this
Click the ‘SVG To Custom Paint’ button here, and you will be directed to the next page.
In the bottom-left corner, you will see the ‘Pick SVG file’ button. From here, you can select an SVG from your local system. Next, upload the file and enable the ‘Responsive’ toggle button as shown.
Then click Generate Code and a code will be generated and you can simply copy the code from the Copy Icon Button.
3. Now get to your code editor and create a new file with a name that best suits the svg asset like “home_icon.dart”. It’s up to you how you are gonna structure the files. Now paste that copied code in the dart file like this
4. Now here is the main thing, you have to remove all code before
class RPSCustomPainter extends CustomPainter
and your file should look like this
5. Change the class name according to the svg asset like “HomeIcon”.
Now we have two things to do, setup color change functionality so if you want to change the color you can do it, and the second size of the icon.
Here is the code you have to paste before the paint function.
final Color? color;
// update constructor name according to your class name
const HomeIcon({this.color});
static Size s(double w) => Size(w, w);
and the file should look like this
The second last step is to update the color so find a keyword using CTRL+F and search for “fill.color”. This will show you where and how many times ‘fill.color’ appears in your file, as shown below:
and just put “color ?? ” in that specific line like this and do not change anything else.
paint_0_fill.color = color ?? Color(0xff7C7C7C).withOpacity(1.0);
and your file should look like this
just do this for every “fill.color” that you find.
Don’t worry this is the last step of how you can use this file as a replacement for an SVG file and here it is
Center(
child: CustomPaint(
painter: OrderIcon(color: Colors.red),
size: Size(10, 10),
),
),
Hurray! now you can render fast any svg without an external package and increase Flutter app performance.
At the end just give a👏 and do follow if you learned something new from it. Thank you so much.