Flutter中如何避免页面显示图片URL而非正常加载展示网络图片
问题原因
你当前的代码直接使用Text组件渲染urlImage字段,只会输出纯文本的链接地址,要展示图片需要使用Flutter的网络图片加载组件。
修复方案
将ListView.builder中ListTile的相关代码替换为以下内容即可,同时适配了空链接、加载异常的兜底场景:
itemBuilder: (context, index) => Card( key: ValueKey(_foundHerbs[index]["id"]), color: Colors.blueAccent, elevation: 4, margin: const EdgeInsets.symmetric(vertical: 10), child: ListTile( // 原leading的id挪到subtitle展示,leading放植物图片 leading: SizedBox( width: 50, height: 50, child: _foundHerbs[index]["urlImage"].isNotEmpty ? Image.network( _foundHerbs[index]["urlImage"], fit: BoxFit.cover, // 图片加载中显示进度环 loadingBuilder: (context, child, loadingProgress) { if (loadingProgress == null) return child; return const Center( child: CircularProgressIndicator(strokeWidth: 2, color: Colors.white,), ); }, // 图片加载失败显示破损图标 errorBuilder: (context, error, stackTrace) { return const Icon(Icons.broken_image, color: Colors.white70); }, ) // 无图片链接时显示占位图标 : const Icon(Icons.image_not_supported, color: Colors.white70), ), title: Text( _foundHerbs[index]['name'], style: const TextStyle(color: Colors.white), ), subtitle: Text( 'ID: ${_foundHerbs[index]["id"].toString()}', style: const TextStyle(color: Colors.white70), ), ), ),
补充说明
- 可以根据自己的需求调整图片的宽高、展示位置,比如要把图片放在名称下方,就把图片组件放到
subtitle参数即可 - 如果需要图片缓存、更丰富的加载效果,可以使用第三方库
cached_network_image替换Image.network,用法基本一致 - 记得给图片组件设置固定宽高,避免图片加载完成后布局发生跳变
内容的提问来源于stack exchange,提问作者Noel Powell
相关产品推荐
相关产品推荐

