在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