Flutter实现卡片左侧阴影并向右渐变效果的方法
实现左侧渐变阴影的方案
你可以放弃使用Card的elevation属性,改用Stack嵌套渐变阴影层或ShaderMask遮罩的方式,实现左侧阴影向右逐渐淡化的效果,以下是两种可行的实现代码:
方案一:Stack + 渐变阴影层
通过堆叠一个带线性渐变的阴影容器在内容容器下方,精准控制阴影从左到右的淡化效果:
Container( width: MediaQuery.of(context).size.width * 0.45, height: MediaQuery.of(context).size.height * 0.15, child: Stack( children: [ // 左侧渐变阴影层 Positioned( left: -8, // 阴影向左延伸的距离 top: 0, bottom: 0, width: MediaQuery.of(context).size.width * 0.45 + 8, child: Container( decoration: BoxDecoration( borderRadius: BorderRadius.circular(20), gradient: LinearGradient( begin: Alignment.centerLeft, end: Alignment.centerRight, colors: [ Colors.black.withOpacity(0.3), // 左侧阴影浓度 Colors.transparent, // 右侧完全透明 ], ), ), ), ), // 上层内容容器(可替换为原Card组件) Container( width: MediaQuery.of(context).size.width * 0.45, height: MediaQuery.of(context).size.height * 0.15, decoration: BoxDecoration( color: Colors.white, borderRadius: BorderRadius.circular(20), ), child: Center(child: Text("内容区域")), ), ], ), )
方案二:ShaderMask实现渐变阴影
通过ShaderMask给阴影添加线性渐变遮罩,让阴影过渡更贴合容器圆角:
Container( width: MediaQuery.of(context).size.width * 0.45, height: MediaQuery.of(context).size.height * 0.15, child: ShaderMask( shaderCallback: (bounds) { return LinearGradient( begin: Alignment.centerLeft, end: Alignment.centerRight, colors: [Colors.black.withOpacity(0.3), Colors.transparent], ).createShader(bounds); }, blendMode: BlendMode.srcIn, child: Container( decoration: BoxDecoration( borderRadius: BorderRadius.circular(20), boxShadow: [ BoxShadow( color: Colors.black, blurRadius: 10, offset: Offset(-5, 0), // 阴影向左偏移 ), ], ), child: Container( decoration: BoxDecoration( color: Colors.white, borderRadius: BorderRadius.circular(20), ), child: Center(child: Text("内容区域")), ), ), ), )
可调参数说明
- 修改
LinearGradient中colors的透明度值,控制阴影深浅过渡 - 调整
BoxShadow的blurRadius(模糊程度)和offset(偏移距离),优化阴影形态 - 若需要保留
Card的内置特性,可将方案中的内容容器替换为原Card组件
内容的提问来源于stack exchange,提问作者Rahul Pandey
相关产品推荐
相关产品推荐

