Categories
Flutter Mobile Development

How to use SVG in flutter

Flutter does not natively support SVG’s. See How to get around this
limitation

Flutter makes it quite easy to work with images format such as JPG and PNG’s. Support for svg images is however not available out of the box. If you try to use an svg file with functions such as Image.asset(), you will see the following error

What is SVG?

Image formats can roughly be divided into raster and vector graphics.

Raster: Raster file formats store data related to each individual pixel.

Vector: In this file format store data as a geometric description. i.e image data is stored as lines, paths, ellipses etc. This allows for higher resolutions.


Examples of raster file formats are Jpeg/Png. These are great formats when we work with images such as photographs.


Svg is preferred If your image has vector artifacts that are easy to scale (shapes, flat/linear colours, etc).

how to use svg images in flutter?

Since flutter does not support svg image format out of box we need to rely on a plugin “flutter svg”, you can get it at pub.dev

Here is a quick overview on how to use the package to display svg’s,

  • create app ( skip, if you already have an app to work with)
  • add package to pubspec.yaml
  • download package by running
  • ‘$flutter packages get’
  • import the flutter svg package into the required dart file
  • call SvgPicture.asset to display svg

This is an excerpt from main.dart.

import 'package:flutter/material.dart';
    import 'package:flutter_svg/flutter_svg.dart';

    void main() => runApp(MyApp());

    class MyApp extends StatelessWidget {
      final String assetName = 'assets/empty-state.svg';

      // This widget is the root of your application.
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          title: 'Flutter Demo',
          home: Scaffold(
            appBar: AppBar(
              title: Text("SVG example"),
            ),
            body: Center(
              child: Container(
                width: 250.0,
                height: 300.0,
                child: SvgPicture.asset(assetName, semanticsLabel: 'Empty state'),
              ),
            ),
          ),
        );
      }
    }

This is what we end up with

Quick Summary

  • Support for svg image format does not exist out of box ( for now)
  • Use a plugin like flutter-svg

Code

Download the code here.

If you find this code useful please give it a star so that others may find it too 🙂

Sign up to be notified of new posts. I promise i won’t spam you.

Leave a Reply

Your email address will not be published.