在Flutter / Dart中显示来自字符串的svg

时间:2019-03-19 12:39:28

标签: svg dart flutter

我正在尝试从svg字符串向屏幕显示图像。

我正在使用https://pub.dartlang.org/packages/flutter_svg来支持svg。

final String svgAsString = '''<?xml version="1.0" encoding="UTF-8"?>
<svg xmlns="http://www.w3.org/2000/svg" width="109" height="109" viewBox="0 
0 109 109">
<g id="kvg:StrokePaths_080a1" style="fill:none;stroke:#000000;stroke- 
width:3;stroke-linecap:round;stroke-linejoin:round;">
<path id="kvg:080a1-s1" 
d="M20.22,18.74c0.77,0.77,0.79,2.14,0.8,3.05C21.38,62,20.62,75,11.5,89.39"/>
</g>
</svg>''';

我无法将其渲染到图像小部件或绘制到画布上。我已经尝试过两种方法,但是却一无所获。

我将在下面粘贴的完整代码:我不确定是否在正确的轨道上。

import 'dart:async';
import 'dart:ui';

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

 class KanjiGradeGenerator extends StatefulWidget {
     @override
     _KanjiGradeState createState() => _KanjiGradeState();
 }

 class _KanjiGradeState extends State<KanjiGradeGenerator> {

 _KanjiGradeState() {}

displaySVG() async {

<g id="kvg:StrokePaths_080a1" style="fill:none;stroke:#000000;stroke- 
width:3;stroke-linecap:round;stroke-linejoin:round;">
<path id="kvg:080a1-s1" 
d="M20.22,18.74c0.77,0.77,0.79,2.14,0.8,3.05C21.38,62,20.62,75,11.5,89.39"/>
</g>
</svg>''';

final DrawableRoot svgRoot = await svg.fromSvgString(rawSvg, rawSvg);

final Picture picture = svgRoot.toPicture();

PictureRecorder picRec;
Canvas can = Canvas(picRec);

setState(() {
  can.drawPicture(picture);
});
}

Widget build(BuildContext context) {
    return new Scaffold(
      body: Container(
        child: displaySVG()
      ),
    );
 }
}

我收到的错误是:

  

I / flutter(7791):类型'Future'不是类型'Widget'的子类型

2 个答案:

答案 0 :(得分:0)

您可以使用FutureBuilder小部件显示图像。

class KanjiGradeGenerator extends StatefulWidget {
  @override
  _KanjiGradeGeneratorState createState() => _KanjiGradeGeneratorState();
}

class _KanjiGradeGeneratorState extends State<KanjiGradeGenerator> {
  final rawSvg = 'YOUR_PATH';

  displaySvg() async {
    final DrawableRoot svgRoot = await svg.fromSvgString(rawSvg, rawSvg);
    return await svgRoot.toPicture().toImage(500, 500);
  }
  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
      future: displaySvg(),
      builder: (context,snapshot){
        return Container(
          child: snapshot.data,
        );
      },
    );
  }
}

答案 1 :(得分:0)

尽管 documentation 建议这样做:

final DrawableRoot svgRoot = await svg.fromSvgString(rawSvg, rawSvg);

我发现将其转换为 Widget 时可能会遇到困难。

如果您的图像字符串是从 Base64 编码/解码的,那么您可以执行 this

一旦你有了一个字符串,你就可以:

import 'package:flutter_svg/flutter_svg.dart';

String decoded; // Decoded image

@override
Widget build(BuildContext context) {
    return new Scaffold(
      body: Container(
        child: SvgPicture.string(decoded)
      ),
    );
 }