flutter_svg 0.6.3

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

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 SvgPicture.asset(
  assetName,
);

You can color/tint the image like so:

final String assetName = 'assets/icon.svg';
final Widget svgIcon = new SvgPicture.asset(
  assetName,
  color: Colors.red,
);

The default placeholder is an empty box (LimitedBox) - although if a height or width is specified on the SvgPicture, a SizedBox will be used instead (which ensures better layout experience). There is currently no way to show an Error visually, however errors will get properly logged to the console in debug mode.

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

// Will print error messages to the console.
final String assetName = 'assets/image_that_does_not_exist.svg';
final Widget svg = new SvgPicture.asset(
  assetName,
);

final Widget networkSvg = new SvgImage.network(
  'https://site-that-takes-a-while.com/image.svg',
  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';
final String rawSvg = '''<svg viewBox="...">...</svg>''';
final DrawableRoot svgRoot = await svg.fromSvgString(rawSvg, rawSvg);

// If you only want the final Picture output, just use
final Picture picture = svgRoot.toPicture();

// Otherwise, if you want to draw it to a canvas:
// 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 SvgPicture helps to automate this logic, and it provides some convenience wrappers for getting assets from multiple sources and caching the resultant Picture. It does not render the data to an Image at any point; you certainly can do that in Flutter, but you then lose some of the benefit of having a vector format to begin with.

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). To date, the biggest change is deprecating the SvgImage widgets in favor of SvgPicture - it became very confusing to maintain that name, as Pictures are the underlying mechanism for rendering rather than Images.

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.
  • [x] Gradient support (Linear: Mostly done, Radial: finishing this will require newer version of flutter).
  • [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, particularly for definitions).
  • [ ] 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 (PoC implementation so far).
  • [x] 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.
  • [x] 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 © Google.

The Dart logo is from dartlang.org © 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.6.3

  • Consume updated fversion of path_drawing.
  • Fix bug with fill-rule inheritence + example to test.

0.6.2

0.6.1

  • Fixed an issue with stroke and fill inheritence (and added test)
  • General formatting/analyzer cleanup

0.6.0

  • BREAKING Update Flutter version dependencies/package dependencies
  • Print unhandled errors only once, and only in debug mode (000e17f)
  • Add ability to specify a BoxFit and Alignment for SvgPictures (Thanks @sroddy!).
  • Support userSpaceOnUse gradientUnits (@sroddy)
  • Miscellaneous bug fixes
  • Restructure project to match expectations of Flutter tooling

0.5.5

  • Create a new class to encapsulate Paint and assist with inheriting all painting properties.
  • Fixes regression introduced in v0.5.2 where some previously working inheritence stopped working.
  • Support more complex stroke/fill property inheritence.

0.5.4

  • Consume latest path_drawing (and path_parsing) packages to fix issue(s) with smooth curve handling.

0.5.3

  • Revert HttpStatus.OK change - not ready yet for Flutter beta channel

0.5.2

  • Fix bug(s) in processing stroke and fill opacity when stroke/fill are inherited.
  • Fix HTTP network headers for network pictures

0.5.1

  • Consume latest change from path_drawing (fixes exponent validation)

0.5.0

  • Minimum Flutter version is now 0.5.1 (latest beta as of release)
    • Merge in support for Focal Pointed Radial Gradients
    • Use asset directory references in pubspec.yaml
  • Better support for nested <tspan> styles
  • Support for text-anchor attribute
  • Fix <ellipse> parsing bug (ellipses were drawn at half the expected size)
  • Fix <polyline> parsing bug (polylines were incorrectly forced to be closed)

0.4.1

  • Fix bug where widget caused exception in a FittedBox

0.4.0

  • Added width and height properties to SvgPicture
  • Remove deprecated code related to SvgImage
  • Improved reporting of error conditions
    • Unsupported style elements will report an error
    • Unresolvable definitions will report an error
  • Fixed matchesTextDirection
  • Support for text-anchor

0.3.3

  • Fix centering/scaling of canvas when viewBox is not square
  • Improved color parsing

0.3.2

  • Bug fix around caching for tinting/coloring (color was not being properly included in cache keys)

0.3.1

  • Support for tinting/coloring the output
  • Documentation updates

0.3.0

  • This version represents a major rewrite of the widget(s) involved in rendering SVG drawings. This is primarily to support caching and better performance in rendering.
  • New method on DrawableRoot toPicture to create a ui.Picture object from the SVG.
  • Support for caching of Pictures, similar to how framework caches images. This will eventually be configurable, but is not as of this release.

BREAKING CHANGES

  • BREAKING CHANGE: SvgImage, AvdImage, and VectorDrawableImage have been deprecated. They relied on methods that are less efficient than those now surfaced in SvgPicture.
  • BREAKING CHANGE: Size is no longer passed to SvgPicture - its size is determined by parent size.
  • BREAKING CHANGE: clipToViewBox is now called allowDrawingOutsideViewBox. It defaults to false. It should not ordinarily be set to true, as it can allow unexpected memory usage if your vector graphic tries to draw far outside of the viewBox bounds.
  • BREAKING CHANGE: SvgPicture does not support custom ErrorWidgetBuilders at this point in time. However, errors will be properly logged to the console. This is a result of improvements in the loading/caching of drawings.

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/README.md

example

A new Flutter project.

Getting Started

For help getting started with Flutter, view our online documentation.

Use this package as a library

1. Depend on it

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


dependencies:
  flutter_svg: ^0.6.3

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.6.3 Nov 5, 2018 Go to the documentation of flutter_svg 0.6.3 Download flutter_svg 0.6.3 archive
0.6.2 Oct 25, 2018 Go to the documentation of flutter_svg 0.6.2 Download flutter_svg 0.6.2 archive
0.6.1+1 Oct 8, 2018 Go to the documentation of flutter_svg 0.6.1+1 Download flutter_svg 0.6.1+1 archive
0.6.1 Oct 8, 2018 Go to the documentation of flutter_svg 0.6.1 Download flutter_svg 0.6.1 archive
0.6.0 Sep 18, 2018 Go to the documentation of flutter_svg 0.6.0 Download flutter_svg 0.6.0 archive
0.5.5+1 Aug 8, 2018 Go to the documentation of flutter_svg 0.5.5+1 Download flutter_svg 0.5.5+1 archive
0.5.5 Aug 8, 2018 Go to the documentation of flutter_svg 0.5.5 Download flutter_svg 0.5.5 archive
0.5.4 Aug 2, 2018 Go to the documentation of flutter_svg 0.5.4 Download flutter_svg 0.5.4 archive
0.5.3 Jul 31, 2018 Go to the documentation of flutter_svg 0.5.3 Download flutter_svg 0.5.3 archive
0.5.2 Jul 31, 2018 Go to the documentation of flutter_svg 0.5.2 Download flutter_svg 0.5.2 archive

All 26 versions...

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

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

  • Dart: 2.0.0
  • pana: 0.12.6
  • Flutter: 0.11.3

Platforms

Detected platforms: Flutter

References Flutter, and has no conflicting libraries.

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.6
path_drawing ^0.4.0 0.4.0
vector_math ^2.0.4 2.0.8
xml ^3.0.0 3.2.3
Transitive dependencies
collection 1.14.11
path_parsing 0.1.3
petitparser 2.0.2
sky_engine 0.0.99
typed_data 1.1.6
Dev dependencies
flutter_test
mockito ^3.0.0
path ^1.5.1
test ^1.3.0