Render SVG in Flutter app

Flutter natively doesn’t support rendering SVG. But there are some workaround for that. There is a plugging called flutter_svg which provide a solid way of adding SVG to your flutter project.

Add svg plugin

First, open the pubspec.yaml and add a plugin with version under the dependencies.

    
       dependencies:
            flutter_svg: ^0.17.1
    

next open terminal and type 

    
      flutter pub get
    

And it will download the required plugin for your project.

Next you have to import the plugin the file which you are going to use.

    
      import 'package:flutter_svg/flutter_svg.dart';
    

Load SVG from asset

First, go and create the folder called images in the root structure and add any SVG image which you like.

Then open the pubspec.yaml and specify your file name under the assets.

Next you can load the file from asset as mentioned in below.

    
       SvgPicture.asset("images/doughnut.svg")
    

Load SVG from network

You can directly load SVG using url also

    
       SvgPicture.network("https://mightymamma.com/wp-content/uploads/2019/03/Tink-Happy-Thoughts.svg")
    

Load SVG from SVG code

If you don’t want to add SVG inside the assets, you can render SVG using it code also. You can use the string method provide by the plugin for this.

    
       SvgPicture.string("<svg height="512" ..... >");
    

Color tint the SVG image

You can change the colour of the image using color property. This will change the colour of the entire image and good for icons kind of single colours images

    
       SvgPicture.asset("images/doughnut.svg",color: Colors.amber,)
    

Also you can change the color blend mode to blend the colors and get different effects.

Add text direction support to SVG

If you want to flip the image horizontally based on the text direction(left to right/ right to left) you have to set matchTextDirection property to true. default it’s false and support only left to right. You can simply check this by wrapping scaffold inside Directionality widget.

    
      Directionality(
        textDirection: TextDirection.rtl,
              child: Scaffold(
              appBar: AppBar(
                title: Text('Material App Bar'),
              ),
              body: Center(
                child: Column(
                  children: [
                            Container(
                              child: SvgPicture.asset("images/doughnut.svg",matchTextDirection: false,),
                            ),
                        ],
                    ),
                ),
        ),
      )
    

What is semanticsLabel property in flutter svg?

The semantic label describes the purpose of the image. This value does not show in the UI. These values used in screen readers to identify the purpose of the image. It best practice to apply this value of the widget needs more accessibility. Also, flutter has semantics widget with more controls of the properties.

You Will Like Also