Flutter图片加载缓存机制的深入探究

网友投稿 1077 2022-05-29

flutter原有的图片缓存机制,是通过PaintingBinding.instance!.imageCache来管理缓存的,这个缓存缓存到的是内存中,每次重新打开APP或者缓存被清理都会再次进行网络请求,大图片加载慢不友好,且增加服务器负担。

https://book.flutterchina.club/chapter14/image_and_cache.html

https://www.jb51.net/article/228697.htm

Flutter 本身是有图片的内存缓存。也是按照 LRU 的算法去管理缓存的。并且缓存池有阈值,我们可以自己去设置我们想要的内存阈值。

Flutter 本身没有提供图片的磁盘缓存,APP 重启之后图片加载流程是会重新走的

Flutter图片加载与缓存机制的深入探究

应用开发中经常会碰到网络图片的加载,通常我们会对图片进行缓存,以便下次加载同一张图片时不用再重新下载,下面这篇文章主要给大家介绍了关于Flutter图片加载与缓存机制的相关资料,需要的朋友可以参考下

今天来学习一下 Flutter 自身是如何加载图片和管理图片的。

Flutter 提供了一个图片控件 Image,Image 定义了若干中加载图片的方式,包括 Image.asset、Image.file、Image.network、Image.memory。

Image内部维护了一个 ImageProvider对象,ImageProvider则真正维护整个图片加载的工作。Widget 本身内部是体现在 RawImage中:

Widget result = RawImage( // Do not clone the image, because RawImage is a stateless wrapper. // The image will be disposed by this state object when it is not needed // anymore, such as when it is unmounted or when the image stream pushes // a new image. image: _imageInfo?.image, debugImageLabel: _imageInfo?.debugLabel, width: widget.width, height: widget.height, scale: _imageInfo?.scale ?? 1.0, color: widget.color, opacity: widget.opacity, colorBlendMode: widget.colorBlendMode, fit: widget.fit, alignment: widget.alignment, repeat: widget.repeat, centerSlice: widget.centerSlice, matchTextDirection: widget.matchTextDirection, invertColors: _invertColors, isAntiAlias: widget.isAntiAlias, filterQuality: widget.filterQuality, ); return result;

这里可以看到 _imageInfo 决定 RawImage如何展示图片。

_imageInfo 则会在图片的每一帧进行重新赋值:

void _handleImageFrame(ImageInfo imageInfo, bool synchronousCall) { setState(() { _replaceImage(info: imageInfo); _loadingProgress = null; _lastException = null; _lastStack = null; _frameNumber = _frameNumber == null ? 0 : _frameNumber! + 1; _wasSynchronouslyLoaded = _wasSynchronouslyLoaded | synchronousCall; }); }

Flutter图片加载与缓存机制的深入探究

Flutter

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:【福利】 加速创新神器!《华为云API精选手册》限时免费领
下一篇:【华为云年中云钜惠收官倒计时】有些机会是等着聪明人来抓住的
相关文章