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

Flutter中如何为CachedNetworkImage添加LinearGradient?

为CachedNetworkImage添加LinearGradient的两种实现方式

你可以通过以下两种方式给CachedNetworkImage添加线性渐变效果:

方法一:使用Stack层叠组件

将CachedNetworkImage作为底层组件,在其上方叠加带渐变效果的Container,让渐变覆盖在图片之上:

Stack(
  children: [
    CachedNetworkImage(
      width: double.infinity,
      height: 130,
      fit: BoxFit.cover, // 建议改为cover,和原实现效果一致
      imageUrl: controller.specialEpisodes[pagePosition].appImage,
      progressIndicatorBuilder: (context, url, downloadProgress) =>
          Shimmer.fromColors(
        baseColor: const Color(0xff21242C),
        highlightColor: Colors.white,
        child: Skeleton(
          width: double.infinity,
          height: SizeConfig.screenHeight * 0.7,
        ),
      ),
      errorWidget: (context, url, error) => const Icon(
        Icons.error,
        size: 100,
        color: Colors.red,
      ),
    ),
    Container(
      width: double.infinity,
      height: 130,
      decoration: BoxDecoration(
        gradient: LinearGradient(
          colors: [
            const Color(0xff21242C),
            const Color(0xff21242C).withOpacity(.2),
            const Color(0xff21242C).withOpacity(.2),
            const Color(0xff21242C).withOpacity(.9),
          ],
          begin: Alignment.topCenter,
          end: Alignment.bottomCenter,
          stops: const [0, 0.2, 0.7, 3],
        ),
      ),
    ),
  ],
)

方法二:利用CachedNetworkImage的imageBuilder参数

通过imageBuilder回调,在图片加载完成后用带渐变装饰的Container包裹图片,无需额外Stack组件:

CachedNetworkImage(
  width: double.infinity,
  height: 130,
  fit: BoxFit.cover,
  imageUrl: controller.specialEpisodes[pagePosition].appImage,
  imageBuilder: (context, imageProvider) => Container(
    decoration: BoxDecoration(
      image: DecorationImage(
        image: imageProvider,
        fit: BoxFit.cover,
      ),
      gradient: LinearGradient(
        colors: [
          const Color(0xff21242C),
          const Color(0xff21242C).withOpacity(.2),
          const Color(0xff21242C).withOpacity(.2),
          const Color(0xff21242C).withOpacity(.9),
        ],
        begin: Alignment.topCenter,
        end: Alignment.bottomCenter,
        stops: const [0, 0.2, 0.7, 3],
      ),
    ),
  ),
  progressIndicatorBuilder: (context, url, downloadProgress) =>
      Shimmer.fromColors(
    baseColor: const Color(0xff21242C),
    highlightColor: Colors.white,
    child: Skeleton(
      width: double.infinity,
      height: SizeConfig.screenHeight * 0.7,
    ),
  ),
  errorWidget: (context, url, error) => const Icon(
    Icons.error,
    size: 100,
    color: Colors.red,
  ),
)

注意:两种方法都建议将fit: BoxFit.contain改为BoxFit.cover,以和你最初的Container+DecorationImage效果保持一致,避免图片拉伸或留白问题。

内容的提问来源于stack exchange,提问作者Khalid

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 12:40:32