Flutter Image

阅读:图片加载原理与缓存

  1. Image是一组合容器,将“图片”的来源(ImageProvider)与绘制(RawImage)组合起来展示图片。
  2. ImageProvider是一个基类,暴露一个通用解析接口resolve给外部使用,返回ImageStream,可以用来监听解析结果ImageInfo。同时ImageProvider实现了通用的缓存逻辑,典型的面向对象编程思想,提取通用部分做成基类,方便复用。
  3. ImageProvider有两个虚函数,需要子类实现,分别是load,用于不同图片源的加载,如网络或本地assets;obtainKey,用于缓存key,区分是否同一缓存对象,如网络图片的url或本地图片的文件路径。
  4. AssetsImage源码里有一个Flutter团队对于性能优化的有意思的一个实现,对于速度快的异步调用转换为同步返回,以尽量在同一帧绘制中展示图片,如注释:
@override
  Future obtainKey(ImageConfiguration configuration) {
    // This function tries to return a SynchronousFuture if possible. We do this
    // because otherwise showing an image would always take at least one frame,
    // which would be sad. (This code is called from inside build/layout/paint,
    // which all happens in one call frame; using native Futures would guarantee
    // that we resolve each future in a new call frame, and thus not in this
    // build/layout/paint sequence.)

你可能感兴趣的:(随笔,Flutter)