flutter自定义实现图片的加载

本文探讨如何在Flutter中避免网络图片重复加载,通过自定义实现,利用MD5算法生成图片URL的KEY并存储在本地,提升用户体验。提供源码分析及简单实现步骤,并分享GitHub链接供参考。
摘要由CSDN通过智能技术生成

在flutter中,默认的图片加载是缓存在内存中的,那么意味着我们结束应用程序后再次进入程序需要再次通过网络请求去加载一些图片资源,在用户的网络情况不是特别好的情况下就会造成不太良好的体验,网上也有一些技术大牛发布了一些加载库,确实厉害。当然别人能实现的我们自己也能实现,一直用别人的虽然节省了时间但不如自己亲自实现香,特别是这种小东西(比较大型的诸如Bloc这些状态管理框架还是随着自己对源码的掌握程度慢慢来,开发时间成本较高,肯定先用大牛的了。),如果自己实现或许能够提升那么一丢丢自己对flutter源码的认知。

废话少说,直接一步一步探究实现过程:

Image(image:?,)

我们在使用的时候这样去获取一个图片,这里点击进去可以发现它需要的是一个

ImageProvider 对象,这是一个抽象类,我们点进源码查看寻找它的实现类,我们可以发现
NetworkImage 这个类,我们平时在调用网络图片的时候是这样用的:
Image.network("src")

点击进去可以发现源码是这样的:

Image.network(
    String src, {
    Key? key,
    double scale = 1.0,
    this.frameBuilder,
    this.loadingBuilder,
    this.errorBuilder,
    this.semanticLabel,
    this.excludeFromSemantics = false,
    this.width,
    this.height,
    this.color,
    this.colorBlendMode,
    this.fit,
    this.alignment = Alignment.center,
    this.repeat = ImageRepeat.noRepeat,
    this.centerSlice,
    this.matchTextDirection = false,
    this.gaplessPlayback = false,
    this.filterQuality = FilterQuality.low,
    this.isAntiAlias = false,
    Map<String, String>? headers,
    int? cacheWidth,
    int? cacheHeight,
  }) : image = ResizeImage.resizeIfNeeded(cacheWidth, cacheHeight, NetworkImage(src, scale: scale, headers: headers)),
       assert(alignment != null),
       assert(repeat != null),
       assert(matchTextDirection != null),
       assert(cacheWidth == null || cacheWidth > 0),
       assert(cacheHeight == null || cacheHeight > 0),
       assert(isAntiAlias != null),
       super(key: key);

可以清晰的看见它其实就是返回了一个NetworkImage对象,故我们要想优化读取网络图片不让其二次加载就可以在这个类中做文章,

我们先看源码:

class NetworkImage extends image_provider.ImageProvider<image_provider.NetworkImage> implements image_provider.NetworkImage {
  /// Creates an object that fetches the image at the given URL.
  ///
  /// The arguments [url] and [scale] must not be null.
  const NetworkImage(this.url, { this.scale = 1.0, this.headers })
    : assert(url != null),
      assert(scale != null);

  @override
  final String url;

  @override
  final double scale;

  @override
  final Map<String, String>? headers;

  @override
  Future<NetworkImage> obtainKey(imag
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值