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討論