如何使用 Dart 将线性渐变动态添加到 SVG

How to dynamically add a lineargradient to an SVG using Dart

我正在使用 Dart (dartlang.org) 生成一些 SVG 图像。 大多数事情都有效,但我在添加渐变时遇到困难。

我有一个这样定义的 SvgSvgElement:

SvgSvgElement svg = new SvgSvgElement();

我添加了这样的 defs 元素:

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

现在我尝试使用这样的字符串片段添加渐变:

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" />
    </linearGradient>
    ''';

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

defsElement.append(element);

从某种意义上说这是有效的,它不会出错,但是当我检查生成的 SVG 时,我得到了嵌套元素,这显然是错误的:

...<defs>
<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">
            </stop>
        </stop>
    </stop>
</lineargradient>
</defs>...

这里我有点不知所措。有一些文档,但是没有例子,很难看懂。

任何帮助将不胜感激,
此致,
亨德里克·简

自闭合标签不 HTML5 兼容,Dart 仅支持 HTML5.
这有效:

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>
    </linearGradient>
    ''';