How to dynamically add a lineargradient to an SVG using Dart


I am using Dart ( to generate some SVG images.
Most things work, but I am having difficulties adding a gradient.

I have an SvgSvgElement defined like this:

SvgSvgElement svg = new SvgSvgElement();

I have added a defs element like this:

SvgElement defsElement = new SvgElement.tag('defs');

And now I try to add a gradient using a string fragment like this:

var str = '''
    <linearGradient id="def_2" x1="2557" y1="5281" x2="2603" y2="5253">
    <stop offset="0" stop-color="#f32b2b" />
    <stop offset="0.75993413" stop-color="#fcc0c0" />
    <stop offset="1" stop-color="#df2323" />

Element element = new Element.html(
    validator: new NodeValidatorBuilder()
      ..allowElement('lineargradient', attributes: ['id', 'x1', 'y1', 'x2', 'y2'])
      ..allowElement('stop', attributes: ['offset', 'stop-color', 'stop-opacity'])


This works in the sense that it doesn’t give errors, but when I inspect the resulting SVG, I get nested elements, which is clearly wrong:

<lineargradient id="def_1" x1="1624" y1="5847" x2="1673" y2="5886">
    <stop offset="0" stop-color="#f32b2b">
        <stop offset="0.75993413" stop-color="#fcc0c0">
            <stop offset="1" stop-color="#df2323">

I am a bit at a loss here. There is some documentation, but without examples, it is difficult to understand.

Any help will be appreciated,
Hendrik Jan


Self-closing tags are not HTML5 compliant and Dart only supports HTML5.
This works:

var str = '''
    <linearGradient id="def_2" x1="2557" y1="5281" x2="2603" y2="5253">
    <stop offset="0" stop-color="#f32b2b"></stop>
    <stop offset="0.75993413" stop-color="#fcc0c0"></stop>
    <stop offset="1" stop-color="#df2323"></stop>

Answered By – Günter Zöchbauer

Answer Checked By – Clifford M. (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *