步骤
1.在根目录建立一个文件夹,名称建议叫images
2.在此文件夹下建立两个文件夹,一个为2.0x
,一个为3.0x
,分别放置2倍图和3倍图,正常的图片直接放置到images
文件夹下
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
是官方注释的,我是直接就解开了,然后把下方的图片路径写好,编译却出现如下错误:
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.在代码中调用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')