Flutter中如何为Container添加顶部阴影及左右顶部半长阴影线条
实现Container顶部阴影+左右半高阴影线条的方案
我懂你想要的效果——顶部有完整的阴影,左右两侧的阴影只从顶部延伸到容器一半的高度对吧?你当前的代码只实现了基础的顶部阴影,没法单独控制左右阴影的高度,咱们用Stack来组合元素就能搞定这个需求。
解决思路
原生的BoxShadow是作用于整个容器的,没办法单独限定阴影的高度范围,所以我们可以:
- 用
Stack作为父组件,把主容器和左右两个阴影容器叠放在一起 - 主容器只保留顶部的阴影效果
- 在左右两侧分别放置一个高度为原容器一半的小容器,只添加单侧的阴影,模拟出半高的阴影线条
完整代码示例
class HomePage extends StatelessWidget { @override Widget build(BuildContext context) { final containerHeight = 500.0; final shadowLineHeight = containerHeight / 2; final shadowWidth = 2.0; // 控制阴影线条的宽度 return Scaffold( backgroundColor: Colors.white, body: Center( child: Padding( padding: const EdgeInsets.all(30.0), child: ClipRRect( borderRadius: BorderRadius.circular(30.0), child: Stack( children: [ // 主容器 Container( height: containerHeight, decoration: BoxDecoration( borderRadius: BorderRadius.vertical(top: Radius.circular(30.0)), color: Colors.blue, boxShadow: [ BoxShadow( color: Colors.grey.withOpacity(0.5), offset: Offset(0.0, -2.0), // 顶部阴影向下偏移 blurRadius: 6.0, spreadRadius: 1.0, ), ], ), ), // 左侧半高阴影线条 Positioned( left: 0, top: 0, height: shadowLineHeight, width: shadowWidth, child: Container( decoration: BoxDecoration( boxShadow: [ BoxShadow( color: Colors.grey.withOpacity(0.5), offset: Offset(-2.0, 0.0), // 左侧阴影向左偏移 blurRadius: 6.0, spreadRadius: 1.0, ), ], ), ), ), // 右侧半高阴影线条 Positioned( right: 0, top: 0, height: shadowLineHeight, width: shadowWidth, child: Container( decoration: BoxDecoration( boxShadow: [ BoxShadow( color: Colors.grey.withOpacity(0.5), offset: Offset(2.0, 0.0), // 右侧阴影向右偏移 blurRadius: 6.0, spreadRadius: 1.0, ), ], ), ), ), ], ), ), ), ), ); } }
代码说明
- 把容器高度和阴影线条高度抽成了变量,方便后续快速调整
- 主容器的阴影调整了
offset为(0.0, -2.0),让阴影集中在顶部区域 - 左右两侧的
Positioned容器高度设为原容器的一半,只添加单侧的阴影,通过offset控制阴影方向,模拟出半高的阴影线条效果 - 调整了
blurRadius和spreadRadius让阴影看起来更自然,你可以根据自己的视觉需求修改这些参数
内容的提问来源于stack exchange,提问作者gopinath




