You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

离线场景展示本地图片遇ArgumentError错误求解决方案

问题根源

你传空字符串给NetworkImage时,它会默认解析成file:///这个无效URI——因为没指定主机地址,所以直接触发ArgumentError。另外原有代码没处理离线时网络图片加载失败的场景,没法自动切换到本地图。

解决办法

1. 先修复空URL引发的错误

直接通过条件判断,当photoUrl为空时,用本地资源图替代NetworkImage:

FadeInImage(
  height: 250,
  width: 300,
  placeholder: AssetImage('images/profile.jpg'),
  image: (user?.photoUrl != null && user!.photoUrl.isNotEmpty) 
      ? NetworkImage(user.photoUrl) 
      : AssetImage('images/profile.jpg'),
)

2. 处理离线场景(自动切换本地图)

如果要实现离线时自动展示本地图,推荐使用cached_network_image包,它会自动缓存网络图片,离线时优先调用缓存,缓存失效或无缓存时展示本地占位图:

第一步:添加依赖

在项目的pubspec.yaml中添加:

dependencies:
  flutter:
    sdk: flutter
  cached_network_image: ^3.2.3 # 可替换为最新版本

第二步:替换原有代码

CachedNetworkImage(
  height: 250,
  width: 300,
  // 加载过程中展示本地图
  placeholder: (context, url) => Image.asset('images/profile.jpg'),
  // 网络图片地址,空值会自动触发errorWidget
  imageUrl: user?.photoUrl ?? '',
  // 加载失败(包括离线无缓存)时展示本地图
  errorWidget: (context, url, error) => Image.asset('images/profile.jpg'),
)

这样既解决了空URL报错的问题,又实现了离线时展示本地图的需求。

内容的提问来源于stack exchange,提问作者Eain Hmun Khin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 11:47:40