Flutter cached_network_image图片缓存异常/加载失败优化

摘要:
图像如果您希望具有占位符功能并在另一个小部件中使用图像提供程序,则可以提供imageBuilder:CachedNetworkImage、图像加载失败:404403等。如果您使用CachedNetworkImageProvider,则错误消息如下:I/translator:CacheManager:Failedtownloadfilefromhttps://pic.xx.com/28000.jpgwitherror:I/flutter:SocketException:Failedhostlookup:'pic.xx.com'I/flutter:CacheManager:无法下载文件fromhttps://pic.xx.com/23730.jpgwitherror:I/flutter:SocketException:Failedhostlookup:'pic.aotorun.com'I/flutter:CacheManager:未能从服务器下载文件错误:I/flutter:无效参数:未指定URI中的主机/flutter:CacheManager:未能从服务器卸载文件错误:I/flutter:无效变量:未指定URII中的主机/flutter:CCacheManager:未能下载文件fromhttps://i1.xx.com/623946/4c71965fac192ebe.jpgwitherror:I/flutter:HttpException:Novalidstatuscode.Statuscodewas404I/flutter:CacheManager:Failedtodownloadfilefromhttps://i1.xx.com/623946/4c71965fac192ebe.jpgwitherror:I/flutter:HttpException:Novalidstatuscode.Statuscodewas404如果它是CachedNetworkImage,则如下所示:I/flitter:Path:I/flitter:/data/user/0/com。实例xx/cache/libCachedImageData/68b03f20-1fa4-11ea-9f10-49083fd8fc8f.jpegI/flitter:蒸气蒸气蒸气蒸气如何解决这个问题?

很多应用都会这么操作,把一些图像进行缓存可以提升用户体验,也能减轻资源浪费,这里以cached_network_image为例。它可以将网络图像进行本地缓存,在需要的时候直接加载,提供了两个使用方法:

CachedNetworkImage(
        imageUrl: "http://via.placeholder.com/350x150",
        placeholder: (context, url) => CircularProgressIndicator(),
        errorWidget: (context, url, error) => Icon(Icons.error),
     ),

使用以上代码的同学可能知道,在加载之前默认的loading会铺满整个视图,不太好看,所以我们还是可以修下:

CachedNetworkImage(
                                imageUrl: '${bannerList[index]['image']}',
                                placeholder: (context, url) => Container(
                                     130,
                                    height: 80,
                                    child: Center(
                                        child: CircularProgressIndicator(
                                            strokeWidth: 2,
                                        ),
                                    ),
                                ),
                                errorWidget: (context, url, error) => Icon(Icons.error),
                                fit: BoxFit.cover,
                            ),

CachedNetworkImage可以直接使用,也可以通过ImageProvider使用。

Image(image: CachedNetworkImageProvider(url))

如果您想同时拥有占位符功能和要在另一个窗口小部件中使用imageprovider,则可以提供imageBuilder:

CachedNetworkImage(
  imageUrl: "http://via.placeholder.com/200x150",
  imageBuilder: (context, imageProvider) => Container(
    decoration: BoxDecoration(
      image: DecorationImage(
          image: imageProvider,
          fit: BoxFit.cover,
          colorFilter:
              ColorFilter.mode(Colors.red, BlendMode.colorBurn)),
    ),
  ),
  placeholder: (context, url) => CircularProgressIndicator(),
  errorWidget: (context, url, error) => Icon(Icons.error),
),

图像加载失败:404,403等

如果你使用了CachedNetworkImageProvider的话,错误信息如:

I/flutter (21047): CacheManager: Failed to download file from https://pic.xx.com/28000.jpg with error:
I/flutter (21047): SocketException: Failed host lookup: 'pic.xx.com' (OS Error: No address associated with hostname, errno = 7)
I/flutter (21047): CacheManager: Failed to download file from https://pic.xx.com/23730.jpg with error:
I/flutter (21047): SocketException: Failed host lookup: 'pic.aotorun.com' (OS Error: No address associated with hostname, errno = 7)
I/flutter (21047): CacheManager: Failed to download file from  with error:
I/flutter (21047): Invalid argument(s): No host specified in URI 
I/flutter (21047): CacheManager: Failed to download file from  with error:
I/flutter (21047): Invalid argument(s): No host specified in URI 
I/flutter (21047): CacheManager: Failed to download file from https://i1.xx.com/623946/4c71965fac192ebe.jpg with error:
I/flutter (21047): HttpException: No valid statuscode. Statuscode was 404
I/flutter (21047): CacheManager: Failed to download file from https://i1.xx.com/623946/4c71965fac192ebe.jpg with error:
I/flutter (21047): HttpException: No valid statuscode. Statuscode was 404

如果是CachedNetworkImage则如下:

I/flutter(21047):Path:

I/flutter(21047):/data/user/0/com.example.xx/cache/libCachedImageData/68b03f20-1fa4-11ea-9f10-49083fd8fc8f.jpeg
I/flutter(21047): ════════════════════════════════════════════════════════════════════════════════════════════════════
I/flutter(21047):Another exception was thrown:Exception:Could notinstantiate image codec.

如何解决?

从文档提供的资料来看,没有对应的解决方案,在issues中我看到大量提出该问题的疑惑,都是在问如何解决的,但目前来看也没有相应的解决方案。其中看到最新的维护人员的回复:

I'd expect that the user of this library makes sure that the url is completely valid,
==>我希望该库的用户确保网址完全有效,

这是理想的状态,但如果图片资源涉及到第三方存储,这就难免出现意外。请求出错的情况包括但不限于:

  • 404,图片不存在
  • 403,无权限访问
  • 无效图片资源,比如占位符并不是有效图像
  • 网络不通
  • ……

这样一看,处理起来确实麻烦,因为有时间差,即使能从返回信息来处理,但回调超时体验上就会造成体验不好。如果是能有效控制维护的数据和API当然可以像官方所说的一样,确保图片资源有效,不管是增删还是301跳转等都好处理,但这不现实。

问题还没解决,有最新进展会继续更……

解决方法一:

 precacheImage(
        CachedNetworkImageProvider(image),
        context, onError: (e, stackTrace) {
      print(('Image failed to load with error:$e'));
      setState(() {
        imgCheck = false;
      });
    });

使用precacheImage方法进行图片预加载,该方法有一个回调onError,它会读取缓存中是否存在err,如果存在,你就可以做点什么了?经测试该方法能解决图像404和网络异常导致的问题。但对于图片URL存在真实有效,却不是一个有效图片这个没法判断。

继续。。。

免责声明:文章转载自《Flutter cached_network_image图片缓存异常/加载失败优化》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇linux安装mysql5.7及相关环境配置PHP 这个设置 ini_set('memory_limit', '200M') 的生效时间下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

flutter报错:Waiting for another flutter command to release the startup lock..

在flutter开发过程中,运行flutter命令,flutter doctor 或者flutter run等命令,如果出现Waiting for another flutter command to release the startup lock..    只要进入flutter sdk 目录,然后找到bin/cache/lockfile文件,删除后再...

Flutter 实现 3des 加密

本人掘金文章 1.  介绍 目的:该插件为 ECB模式 3des 加密,解决 flutter => java后台 => 硬件 相联系的需求 (需保证App端、java服务端、硬件三方加密结果一致); 现有的 pub.dev 插件如(flutter_3des, flutter_des, des_plugin)加密后的结果均和 java、硬件加密的...

flutter SnackBar 底部消息提示

具有可选操作的轻量级消息提示,在屏幕的底部显示 文档:https://api.flutter.dev/flutter/material/SnackBar-class.html demo: import 'package:flutter/material.dart'; class SnackBarDemo extendsStatefulWidget {...

干货 | 把Flutter扩展到微信小程序端的探索

Google Flutter是一个非常优秀的跨端框架,不仅可以运行在Android、 iOS平台,而且可以支持Web和桌面应用。在国内小程序是非常重要的技术平台,我们也一直思考能否把Flutter扩展到小程序端?我们团队之前已经开源了Alita项目(https://github.com/areslabs/alita),Alita可以把React Nati...

BottomNavigationBar 自定义 底部导航条

在flutter中,BottomNavigationBar 是底部导航条,可以让我们定义底部 Tab 切换,bottomNavigationBar是 Scaffold 组件的参数。 BottomNavigationBar 常见的属性 items :List底部导航条按钮集合 iconSize :icon currentIndex :默认选中第几个 onT...

客户端软件GUI开发技术漫谈:原生与跨平台解决方案分析

原生开发应用开发 Microsoft阵营的 Winform WinForm是·Net开发平台中对Windows Form的一种称谓。 如果你想深入的美化UI,需要耗费很大的力气,对于目前主流的CSS样式表来讲,美化Winform的界面以及自定义控件是需要耗费更多的时间的。 WPF 基于XML+C#+CSS的呈现方式让它在UI上有了更加灵活的设计宽度 WPF...