Flutter CachedNetworkImageProvider-如何在错误时显示本地默认图像?

时间:2019-02-17 05:02:12

标签: dart flutter

如果由于某些原因CachedNetworkImageProvider无法获取远程图像,我想显示默认的本地图像:

Container(
  width: 80.0,
  height: 120.0,
  decoration: new BoxDecoration(
    shape: BoxShape.rectangle,
    image: new DecorationImage(
      fit: BoxFit.fill,
      image: new CachedNetworkImageProvider(url),
    ),
  ),
),

3 个答案:

答案 0 :(得分:0)

您可以使用带有errorWidget参数的cached network image插件,链接中说明了安装步骤。这是它的示例实现:

  image: new CachedNetworkImage(
             imageUrl: "http://via.placeholder.com/350x150",
             placeholder: new CircularProgressIndicator(),
             errorWidget: new Image.assets('error.jpg'), // This is what you need
             fit: BoxFit.fill,
             fadeInCurve: Curves.easeIn ,
             fadeInDuration: Duration(seconds: 2),
             fadeOutCurve: Curves.easeOut,
             fadeOutDuration: Duration(seconds: 2),

            ),

您会注意到它还具有其他功能,例如placeholder和动画,因此您将具有更多的修补功能。

答案 1 :(得分:0)

@Abdullah Khan-我结束了:

CachedNetworkImage(
  imageUrl: url,
  placeholder: (context, url) => CircularProgressIndicator(),
  errorWidget: (context, url, error) => GestureDetector(
    onTap: () {
      setAvatar();
    },
    child: Icon(
      Icons.account_circle,
      size: 100.0,
      color: Theme.of(context).primaryColor,
    ),
  ),
  imageBuilder: (context, image) => Hero(
    tag: 'photo',
    child: GestureDetector(
      onTap: () {
        Get.toNamed(Routes.FULLPHOTO,
          arguments: {
            'url': url,
            'name': photoTitle,
            'idx': 0
          });
      },
      child: CircleAvatar(
        backgroundImage: image,
        radius: size,
      ),
    ),
  ),
),

Get.toNamed来自GetX包(非常适合导航和状态管理)。

答案 2 :(得分:0)

@Kamlesh,像这样吗?:

Container(
  margin: EdgeInsets.only(right: 8, left: 8, top: 8, bottom: 8),
  width: 80,
  height: 80,
  decoration: BoxDecoration(
    // borderRadius: BorderRadius.all(Radius.circular(14)),
    // color: Colors.blue.shade200,
    image: DecorationImage(
      fit: BoxFit.contain,
      image: CachedNetworkImageProvider(
        ipath,
      ),
    ),
  ),
),