flutter图片预览_Flutter加载本地图片躺坑记录

本文记录了在Flutter中加载本地图片的步骤,包括在项目根目录创建images文件夹,区分不同分辨率的图片,正确配置pubspec.yaml文件,注意assets字段对齐,以及在代码中使用Image.asset()方法加载图片。同时提到了加载第三方库中图片时需要指定package。
摘要由CSDN通过智能技术生成

步骤

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是官方注释的,我是直接就解开了,然后把下方的图片路径写好,编译却出现如下错误:

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')

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值