加载本地图片步骤
1、在根目录下建立文件夹,也可以建在其它目录下,官方建议命名为images
2.在pubspec.yaml文件中声明本地图片, 每一个使用的本地图片都需要在yaml文件中声明
# To add assets to your application, add an assets section, like this:
# assets:
# - images/a_dot_burr.jpeg
# - images/a_dot_ham.jpeg
# An image asset can refer to one or more resolution-specific "variants", see
# https://flutter.dev/assets-and-images/#resolution-aware.
# For details regarding adding assets from package dependencies, see
# https://flutter.dev/assets-and-images/#from-packages
在使用的时候我们可以把官方的注释打开,按照格式申明我们自己的图片路径:
assets:
- images/girl.jpeg
然后进行编译的时候,会有以下错误提示:
Error detected in pubspec.yaml:
Error on line 44, column 4: Expected a key while parsing a block mapping.
╷
44 │ assets:
│ ^
╵
Please correct the pubspec.yaml file at /Users/CodingSnail/Documents/workspace/FlutterSpace/custom_widget/pubspec.yaml
Process finished with exit code 1
原因是assets前面有一个空格,assets需要与上面的uses-material-design对齐,把它对齐重新编译就好了。
3.在代码中执行加载本地图片,示例:
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('加载本地图片示例'),
),
body: Column(
children: <Widget>[
Image.asset(
'images/girl.jpeg',
),
],
)),
);
}
}
结果展示如下:
WechatIMG1196 (1).png