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

Flutter报_network_image_io 'url' != null断言错误该如何解决

问题原因

这个报错Failed assertion: : _network_image_io 'url' != null : is not true是因为你给Image.network传入的图片链接参数为空导致的。
你代码中直接通过链式取值获取特色图片链接:snapshot.data![i]["_embedded"]["wp:featuredmedia"][0]["source_url"],当部分新闻没有在后台设置特色图片时,这个字段就会返回null,直接传入Image.network就会触发框架的非空断言报错,对应页面就会出现红色错误块。

修复方案

你需要对图片链接做非空判断,空值时显示占位图即可,同时建议对链式取值做空安全处理,避免某个层级字段不存在导致额外报错:

修改后的Image部分代码示例:

// 先安全提取图片链接
final String? imageUrl = snapshot.data?[i]["_embedded"]?["wp:featuredmedia"]?[0]?["source_url"] as String?;

Container(
  decoration: BoxDecoration(
    borderRadius: BorderRadius.circular(10),
  ),
  child: imageUrl != null && imageUrl.isNotEmpty
    ? Image.network(
        imageUrl,
        width: 150,
        height: double.infinity,
        fit: BoxFit.cover,
        // 可选:添加加载错误时的占位处理
        errorBuilder: (context, error, stackTrace) {
          return Container(
            width: 150,
            color: Colors.grey[200],
            child: const Icon(Icons.broken_image, color: Colors.grey),
          );
        },
        // 可选:添加加载中的占位
        loadingBuilder: (context, child, loadingProgress) {
          if (loadingProgress == null) return child;
          return Container(
            width: 150,
            color: Colors.grey[200],
            child: const Center(child: CircularProgressIndicator(strokeWidth: 2)),
          );
        },
      )
    : Container(
        width: 150,
        color: Colors.grey[200],
        child: const Icon(Icons.image_not_supported, color: Colors.grey),
      ),
),
额外优化建议

你当前手动替换HTML标签提取纯文本的写法冗余度很高,可以引入对应HTML解析包直接提取纯文本或者渲染HTML内容,减少重复代码。


内容的提问来源于stack exchange,提问作者Pimpi Rimpà

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 12:24:03