https://segmentfault.com/a/1190000015132238?utm_source=index-hottest
本文详细讲述怎样在flutter项目中使用svg图标。使得读者能够按照本文的操作步骤顺利的在项目中实践。
升级flutter
由于环境中的flutter是0.3.2beta版本,在运行项目的时候出现了提示:需要使用
flutter upgrade
命令来升级flutter
然而出现了这么个错误:
貌似是网络导致的,没有办法,只能重新下一个官方的
由于环境是mac,所以下载mac版本
https://storage.googleapis.co...
下载完毕之后解压缩替换原来的flutter路径就好了。
使用flutter_svg
前言
特意去google了一下,找到这两篇issue
https://github.com/flutter/fl...
https://github.com/flutter/fl...
意思是flutter官方不准备提供svg的全部支持,所以现在是社区有人在维护。
github:https://github.com/dnfield/fl...
新建项目
flutter create flutter_myapp
新增依赖
pubspec.yaml新增:
flutter_svg: ^0.3.2
把svg文件添加到资源中
我们可以去http://www.iconfont.cn/ 找一些svg
svg文件需要全部放在项目根目录的资源文件夹中,文件夹的名称我们可以使用约定,这里选择使用assets。
编辑pubspec.yaml,把上述svg资源全部新增到资源项。
assets:
- assets/close.svg - assets/set.svg - assets/warning.svg - assets/wrong.svg
于是我们可以这么来用:
SvgPicture close = new SvgPicture.asset( "assets/close.svg", color: Colors.grey, );
编辑main.dart
import 'package:flutter/material.dart'; import 'package:flutter_svg/flutter_svg.dart'; 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: new MyHomePage(title: 'Flutter Demo Home Page'), ); } } class MyHomePage extends StatefulWidget { MyHomePage({Key key, this.title}) : super(key: key); final String title; @override _MyHomePageState createState() => new _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> { @override Widget build(BuildContext context) { SvgPicture close = new SvgPicture.asset( "assets/close.svg", color: Colors.grey, ); SvgPicture set = new SvgPicture.asset("assets/set.svg", color: Colors.redAccent); SvgPicture warning = new SvgPicture.asset("assets/warning.svg", color: Colors.blueAccent); SvgPicture wrong = new SvgPicture.asset("assets/wrong.svg", color: Colors.greenAccent); return new Scaffold( appBar: new AppBar( title: new Text(widget.title), ), body: new Column( children: <Widget>[ new Row( children: <Widget>[ new SizedBox( width: 50.0, height: 50.0, child: close, ), new SizedBox( width: 50.0, height: 50.0, child: set, ), new SizedBox( width: 50.0, height: 50.0, child: warning, ), new SizedBox( width: 50.0, height: 50.0, child: wrong, ), ], ) ], ), // This trailing comma makes auto-formatting nicer for build methods. ); } }
效果:
代码:
https://github.com/jzoom/flut...
如有疑问,请加qq群854192563讨论