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

Flutter如何实现容器左右角落渐变效果?

Flutter容器左右角落渐变效果实现方案

要实现容器左右两侧角落的渐变过渡效果,推荐以下两种实用方案:

方法一:Stack叠加渐变层

通过在目标容器上层叠加左右两个渐变容器,精准控制两侧的渐变范围:

Container(
  height: 200,
  width: double.infinity,
  color: Colors.grey[100], // 容器基础背景色
  child: Stack(
    children: [
      // 左侧渐变:从透明过渡到背景色
      Positioned(
        left: 0,
        top: 0,
        bottom: 0,
        width: 50, // 渐变宽度可按需调整
        child: Container(
          decoration: BoxDecoration(
            gradient: LinearGradient(
              begin: Alignment.centerLeft,
              end: Alignment.centerRight,
              colors: [Colors.transparent, Colors.grey[100]!],
            ),
          ),
        ),
      ),
      // 右侧渐变:从背景色过渡到透明
      Positioned(
        right: 0,
        top: 0,
        bottom: 0,
        width: 50,
        child: Container(
          decoration: BoxDecoration(
            gradient: LinearGradient(
              begin: Alignment.centerLeft,
              end: Alignment.centerRight,
              colors: [Colors.grey[100]!, Colors.transparent],
            ),
          ),
        ),
      ),
      // 容器内部内容
      Center(child: Text("带左右渐变的容器")),
    ],
  ),
)

方法二:ShaderMask自定义遮罩

通过遮罩实现对称渐变,代码更简洁,适合需要统一控制渐变比例的场景:

ShaderMask(
  shaderCallback: (Rect bounds) {
    return LinearGradient(
      begin: Alignment.centerLeft,
      end: Alignment.centerRight,
      colors: [Colors.transparent, Colors.white, Colors.white, Colors.transparent],
      stops: [0.0, 0.1, 0.9, 1.0], // 0.1和0.9控制渐变结束的位置
    ).createShader(bounds);
  },
  blendMode: BlendMode.dstIn,
  child: Container(
    height: 200,
    width: double.infinity,
    color: Colors.grey[100],
    child: Center(child: Text("带左右渐变的容器")),
  ),
)

方案对比

  • 方法一:可单独调整左右渐变的宽度、颜色过渡,适合非对称渐变需求;
  • 方法二:通过stops参数精准控制渐变范围,代码更紧凑,适合对称渐变场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 16:25:02