Flutter中如何为Card添加带边框的圆角实色阴影?
解决思路与实现代码
问题原因
你当前的实现有两个核心问题:
Card组件自带默认的背景、内边距和elevation效果,会遮挡外层Container的阴影;- 你设置的
blurRadius:4.0会让阴影模糊,而预期效果是实色无模糊的偏移阴影。
方案一:用嵌套Container替代Card(推荐,可控性更强)
直接用两层Container实现,完全自定义样式:
Container( width: 120, height: 40, // 外层容器负责实色阴影 decoration: const BoxDecoration( boxShadow: [ BoxShadow( color: Color.fromRGBO(0, 0, 0, 0.5), blurRadius: 0, // 取消模糊,得到实色阴影 offset: Offset(3.5, 3.5), ), ], ), // 内层容器模拟Card的边框和内容 child: Container( decoration: BoxDecoration( color: Colors.white, border: Border.all(color: Colors.grey.shade300), // 匹配预期的边框 ), child: const Center( child: Text("1-6 Months"), ), ), )
方案二:保留Card组件的实现
如果必须使用Card,需要清除它的默认样式,并用Stack让阴影层在底层:
Stack( alignment: Alignment.center, children: [ // 阴影层 Container( width: 120, height: 40, decoration: const BoxDecoration( boxShadow: [ BoxShadow( color: Color.fromRGBO(0, 0, 0, 0.5), blurRadius: 0, offset: Offset(3.5, 3.5), ), ], ), ), // Card层,清除默认样式 Card( elevation: 0, // 去掉Card自带的阴影 margin: EdgeInsets.zero, // 清除默认外边距 child: const SizedBox( width: 120, height: 40, child: Center( child: Text("1-6 Months"), ), ), ), ], )
关键调整点
- 将
blurRadius设为0,阴影从模糊效果变为实色偏移,匹配预期的硬边阴影; - 确保阴影层在内容层的下方,避免被背景遮挡;
- 清除Card的默认elevation和margin,避免干扰自定义样式。
内容的提问来源于stack exchange,提问作者Hriday Sarma
相关产品推荐
相关产品推荐

