flutter_svg 0.2.0

  • README.md
  • CHANGELOG.md
  • Example
  • Installing
  • Versions
  • new50

flutter_svg

Pub Build Status Coverage Status

Flutter Logo which can be rendered by this package!

Draw SVG and Android VectorDrawable (XML) files on a Flutter Widget.

Getting Started

This is a Dart-native rendering library. Issues/PRs will be raised in Flutter and flutter/engine as necessary for features that are not good candidates for Dart implementations (especially if they're impossible to implement without engine support). However, not everything that Skia can easily do needs to be done by Skia; for example, the Path parsing logic here isn't much slower than doing it in native, and Skia isn't always doing low level GPU accelerated work where you might think it is (e.g. Dash Paths).

All of the SVGs in the assets/ folder (except the text related one(s)) now have corresponding PNGs in the golden/ folder that were rendered using flutter test tool/gen_golden.dart and compared against their rendering output in Chrome. Automated tests will continue to compare these to ensure code changes do not break known-good renderings.

Basic usage (to create an SVG rendering widget from an asset):

final String assetName = 'assets/image.svg';
final Widget svg = new SvgImage.asset(
  assetName,
  new Size(100.0, 100.0),
);

The default placeholder is an empty box. The default error widget is an ErrorWidget.

You can also specify a placeholder widget and an error widget. The placeholder will display during parsing/loading (normally only relevant for network access).

final ErrorWidgetBuilder customErrorBuilder = (FlutterErrorDetails details) {
  debugPrint(details.toString());
  return new Row(children: const <Widget>[
    const Icon(
      Icons.error,
      color: Colors.red,
    ),
    const Text('Error Loading')
  ]);
};

final String assetName = 'assets/image_that_does_not_exist.svg';
final Widget svg = new SvgImage.asset(
  assetName,
  new Size(100.0, 100.0),
  errorWidgetBuilder: customErrorBuilder,
);

final Widget networkSvg = new SvgImage.network(
  'https://site-that-takes-a-while.com/image.svg',
  new Size(100.0, 100.0),
  loadingPlaceholderBuilder: (BuildContext context) => new Container(
      padding: const EdgeInsets.all(30.0),
      child: const CircularProgressIndicator()),
);

If you'd like to render the SVG to some other canvas, you can do something like:

import 'package:flutter_svg/flutter_svg.dart' as svg;
final svg.DrawableRoot svgRoot = await svg.loadAsset('assets/image.svg');

// Optional, but probably normally desirable: scale the canvas dimensions to
// the SVG's viewbox
svgRoot.scaleCanvasToViewBox(canvas);

// Optional, but probably normally desireable: ensure the SVG isn't rendered
// outside of the viewbox bounds
svgRoot.clipCanvasToViewBox(canvas);
svgRoot.draw(canvas, size);

The SvgImage widget is basically a wrapper around that.

While I'm making every effort to avoid needlessly changing the API, it's not guarnateed to be stable yet (hence the pre-1.0.0 version).

See main.dart for a complete sample.

Use Cases

  • Your designer creates a vector asset that you want to include without converting to 5 different raster format resolutions.
  • Your vector drawing is meant to be static and non (or maybe minimally) interactive.
  • You want to load SVGs dynamically from network sources at runtime.
  • You want to paint SVG data and render it to an image.

TODO

This list is not very well ordered. I'm mainly picking up things that seem interesting or useful, or where I've gotten a request to fix something/example of something that's broken.

  • [ ] Text support.
  • [ ] Gradient support (Linear: Mostly done, Radial: partly done).
  • [x] Dash path support.
  • [ ] Dash path with percentage dasharray values.
  • [ ] More SVG samples to cover more complicated cases (getting there - please file issues for things that don't work!).
  • [ ] Display/visibility support.
  • [x] Unit tests. In particular, tests that validate XML -> Drawable* structures. (Vastly improved as of 0.2.) this is getting there, just need to stay on top of it.
  • [ ] Inheritance of inheritable properties (necessary? preprocess? significant progress, still some rough edges).
  • [ ] Support for minimal CSS/styles? See also svgcleaner (partial - style attribute mostly supported).
  • [ ] XLink/ref support (necessary? partially supported for gradients).
  • [ ] Glyph support?
  • [ ] Markers.
  • [ ] Filters/effects.
  • [ ] Android Vector Drawable support (partial so far).
  • [ ] Caching of image.
  • [ ] The XML parsing implementation is heavy for what this really needs. I've made efforts to keep the API forward-reading-only compatible to eventually be able to use a SAX/XMLReader streaming style parser.
  • [ ] Color swapping/hue shifting/tinting of asset.

Probably out of scope

  • SMIL animations. That just seems crazy. I think it'll be possible to animate the SVG but probably in a more Flutter driven way.
  • Full (any?) CSS support - preprocess your SVGs (perhaps with svgcleaner to get rid of all CSS?)
  • Scripting in SVGs
  • Foreign elements
  • Rendering properties/hints

SVG sample attribution

SVGs in /assets/w3samples pulled from W3 sample files

SVGs in /assets/deborah_ufw provided by @deborah-ufw

SVGs in /assets/simple are pulled from trivial examples or generated to test basic functionality - some of them come directly from the SVG 1.1 spec.

SVGs in /assets/wikimedia are pulled from Wikimedia Commons

Android Drawables in assets/android_vd are pulled from Android Documentation and examples.

The Flutter Logo created based on the Flutter Logo Widget (c) Google.

The Dart logo is from darglang.org (c) Google

Please submit SVGs this can't render properly (e.g. that don't render here the way they do in chrome), as long as they're not using anything "probably out of scope" (above).

CHANGES

0.2.0

  • Fix bug(s) in inheritence (better rendering of Ghostscript_Tiger.svg)
  • Support for <clipPath>s
  • Refactoring of how gradients are handled to enable clipPaths
  • Refactor of SVG shape -> path logic

0.1.4

  • Fix bugs in <radialGradient> percentage handling.
  • Add error widget on error.
  • Add ability to specify error/placeholder widgets.
  • Minor improvement on flutter logo SVG (add missing gradient).
  • Improve docs, unit tests.

0.1.3

  • Add more unit tests and rendering tests (!).
  • Add top level flutter_svg.dart.
  • Fix bugs found in transform matrix logic for skewX and skewY.
  • Minor improvements in handling inheritence for PathFillType.
  • Support gradient spread types (TileModes in Flutter).

0.1.2

  • Bump to path_drawing 0.2.3 (fix arc defect).
  • Handle 'none' in dasharray without throwing exception.
  • Better handling of inheritence and 'none' in fill/stroke/dasharray

0.1.1

  • Handle opacity on groups and inherited/blended opacity.
  • Fixes elements that have both opacity and stroke-opacity or fill-opacity.
  • Improvements for inheritence.
  • Fixes related to unspecified fills on shapes.

0.1.0

Bumping minor version due to internal breaking changes and new support. Works on dev channel as of release (Flutter >= 0.3.6).

  • Refactor DrawableRoot to support top level style definition.
  • Support for dash paths.
  • Support for more inherited attributes.
  • Initial support for @style attributes.
  • Support for rgb() color attribute/styles.
  • Change painting order from stroke first, then fill to fill first, then stroke (matches Chrome rendering of assets/simple/style_attr.svg).

0.0.2

Initial text support. Relies on flutter 0.3.6.

0.0.1

Initial release. Relies on pre-released master.

example/main.dart

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

const List<String> assetNames = const <String>[
  'assets/notfound.svg',
  'assets/flutter_logo.svg',
  'assets/dart.svg',
  'assets/simple/clip_path_3.svg',
  'assets/simple/clip_path_2.svg',
  'assets/simple/clip_path.svg',
  'assets/simple/group_opacity.svg',
  'assets/simple/text.svg',
  'assets/simple/linear_gradient.svg',
  'assets/simple/linear_gradient_2.svg',
  'assets/simple/radial_gradient.svg',
  'assets/simple/rect_rrect.svg',
  'assets/simple/style_attr.svg',
  'assets/w3samples/aa.svg',
  'assets/w3samples/alphachannel.svg',
  'assets/deborah_ufw/new-action-expander.svg',
  'assets/deborah_ufw/new-camera.svg',
  'assets/deborah_ufw/new-gif-button.svg',
  'assets/deborah_ufw/new-gif.svg',
  'assets/deborah_ufw/new-image.svg',
  'assets/deborah_ufw/new-mention.svg',
  'assets/deborah_ufw/new-pause-button.svg',
  'assets/deborah_ufw/new-play-button.svg',
  'assets/deborah_ufw/new-send-circle.svg',
  'assets/deborah_ufw/numeric_25.svg',
  'assets/simple/ellipse.svg',
  'assets/simple/dash_path.svg',
  'assets/simple/nested_group.svg',
  'assets/wikimedia/chess_knight.svg',
  'assets/wikimedia/Ghostscript_Tiger.svg',
];

const List<String> uriNames = const <String>[
  'http://upload.wikimedia.org/wikipedia/commons/0/02/SVG_logo.svg',
  'https://dev.w3.org/SVG/tools/svgweb/samples/svg-files/410.svg',
  'https://upload.wikimedia.org/wikipedia/commons/b/b4/Chess_ndd45.svg',
];

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

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Flutter Demo',
      theme: new ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Flutter SVG Demo'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key key, this.title}) : super(key: key);
  final String title;

  @override
  _MyHomePageState createState() => new _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  final List<VectorDrawableImage> _painters = <VectorDrawableImage>[];
  double _dimension;

  final ErrorWidgetBuilder customErrorBuilder = (FlutterErrorDetails details) {
    debugPrint(details.toString());
    return new Row(children: const <Widget>[
      const Icon(
        Icons.error,
        color: Colors.red,
      ),
      const Text('Error Loading')
    ]);
  };

  @override
  void initState() {
    super.initState();
    _dimension = 365.0;

    for (String assetName in assetNames) {
      _painters.add(
        new SvgImage.asset(
          assetName,
          new Size(_dimension, _dimension),
          errorWidgetBuilder: customErrorBuilder,
        ),
      );
    }

    for (String uriName in uriNames) {
      _painters.add(
        new SvgImage.network(
          uriName,
          new Size(_dimension, _dimension),
          loadingPlaceholderBuilder: (BuildContext context) => new Container(
              padding: const EdgeInsets.all(30.0),
              child: const CircularProgressIndicator()),
        ),
      );
    }
    _painters.add(new AvdImage.asset('assets/android_vd/battery_charging.xml',
        new Size(_dimension, _dimension)));
  }

  @override
  Widget build(BuildContext context) {
    if (_dimension > MediaQuery.of(context).size.width - 10.0) {
      _dimension = MediaQuery.of(context).size.width - 10.0;
    }
    return new Scaffold(
      appBar: new AppBar(
        title: new Text(widget.title),
      ),
      body: new Column(children: <Widget>[
        new Slider(
            min: 5.0,
            max: MediaQuery.of(context).size.width - 10.0,
            value: _dimension,
            onChanged: (double val) {
              setState(() => _dimension = val);
            }),
        // new FlutterLogo(size: _dimension),
        new Expanded(
          child: new GridView.extent(
            shrinkWrap: true,
            maxCrossAxisExtent: _dimension,
            padding: const EdgeInsets.all(4.0),
            mainAxisSpacing: 4.0,
            crossAxisSpacing: 4.0,
            children: _painters.toList(),
          ),
        ),
      ]),
    );
  }
}

Use this package as a library

1. Depend on it

Add this to your package's pubspec.yaml file:


dependencies:
  flutter_svg: "^0.2.0"

2. Install it

You can install packages from the command line:

with Flutter:


$ flutter packages get

Alternatively, your editor might support flutter packages get. Check the docs for your editor to learn more.

3. Import it

Now in your Dart code, you can use:


      import 'package:flutter_svg/flutter_svg.dart';
  
Version Uploaded Documentation Archive
0.2.0 May 20, 2018 Go to the documentation of flutter_svg 0.2.0 Download flutter_svg 0.2.0 archive
0.1.4 May 17, 2018 Go to the documentation of flutter_svg 0.1.4 Download flutter_svg 0.1.4 archive
0.1.3 May 15, 2018 Go to the documentation of flutter_svg 0.1.3 Download flutter_svg 0.1.3 archive
0.1.2 May 14, 2018 Go to the documentation of flutter_svg 0.1.2 Download flutter_svg 0.1.2 archive
0.1.1 May 11, 2018 Go to the documentation of flutter_svg 0.1.1 Download flutter_svg 0.1.1 archive
0.1.0 May 10, 2018 Go to the documentation of flutter_svg 0.1.0 Download flutter_svg 0.1.0 archive
0.0.2 May 6, 2018 Go to the documentation of flutter_svg 0.0.2 Download flutter_svg 0.0.2 archive
0.0.1 May 1, 2018 Go to the documentation of flutter_svg 0.0.1 Download flutter_svg 0.0.1 archive

Analysis

We analyzed this package on May 20, 2018, and provided a score, details, and suggestions below. Analysis was completed with status completed using:

  • Dart: 2.0.0-dev.54.0
  • pana: 0.10.6
  • Flutter: 0.4.4

Scores

Popularity:
Describes how popular the package is relative to other packages. [more]
0 / 100
Health:
Code health derived from static analysis. [more]
100 / 100
Maintenance:
Reflects how tidy and up-to-date the package is. [more]
100 / 100
Overall score:
Weighted score of the above. [more]
50
Learn more about scoring.

Platforms

Detected platforms: Flutter

References Flutter, and has no conflicting libraries.

Suggestions

  • The description is too short.

    Add more detail about the package, what it does and what is its target use case. Try to write at least 60 characters.

  • Package is pre-v1 release.

    While there is nothing inherently wrong with versions of 0.*.*, it usually means that the author is still experimenting with the general direction API.

Dependencies

Package Constraint Resolved Available
Direct dependencies
Dart SDK >=1.19.0 <3.0.0
flutter 0.0.0
meta ^1.1.2 1.1.5
path_drawing ^0.2.3 0.2.3
vector_math ^2.0.4 2.0.6 2.0.7
xml ^3.0.0 3.0.0
Transitive dependencies
collection 1.14.6 1.14.9
matcher 0.12.2+1
petitparser 1.7.6
sky_engine 0.0.99
stack_trace 1.9.2
typed_data 1.1.5
Dev dependencies
flutter_test
mockito ^2.2.3
path ^1.5.1 1.5.1
test ^0.12.34