步驟
1.在根目錄建立一個文件夾,名稱建議叫images
2.在此文件夾下建立兩個文件夾,一個為2.0x,一個為3.0x,分別放置2倍圖和3倍圖,正常的圖片直接放置到images文件夾下

images.png
3.在
pubspec.yaml文件中申明本地圖片:
# The following section is specific to Flutter.
flutter:
# The following line ensures that the Material Icons font is
# included with your application, so that you can use the icons in
# the material Icons class.
uses-material-design: true
# To add assets to your application, add an assets section, like this:
assets:
- images/tupian.png
這里有一個坑,先前這個assets是官方注釋的,我是直接就解開了,然后把下方的圖片路徑寫好,編譯卻出現(xiàn)如下錯誤:
Error on line 29, column 4 of pubspec.yaml: Expected a key while parsing a block mapping.
assets:
^
pub get failed (65)
原因是assets前面有一個空格,assets需要與上面的uses-material-design對齊,把它對齊重新編譯就好了。
4.在代碼中調(diào)用Image.asset()方法加載本地圖片展示,示例:
import 'package:flutter/material.dart';
void main() => runApp(new MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'Welcome to Flutter',
home: new Scaffold(
appBar: new AppBar(
title: new Text('Welcome to Flutter'),
),
body: new Center(
child: new Image.asset("images/tupian.png") //路徑要寫全
),
),
);
}
}
如果是加載第三方依賴庫中的圖片,需要在路徑后面申明包名路徑:
new Image.asset("images/tupian.png", package: 'my_package')