Flutter中如何为Material Card组件添加标题装饰?
Flutter 实现带突出独立标题框的Card方案
首先明确结论:Material 设计规范未对Card的标题样式做强制约束,原生Card组件没有内置突出式标题框的现成属性,但完全支持通过自定义布局实现目标效果,不存在规范冲突。
你现有代码里的Card圆角、边框配置是正确的,要做出突出式挂在边框上的标题框,核心用Stack层叠布局实现即可,不需要修改组件源码,也不需要引入第三方依赖:
- 底层放置你已经配置好样式的Card,注意给Card顶部增加足够的内边距,预留出标题的占位空间,避免卡片内容被标题遮挡
- 上层用
Positioned定位,把单独设置好边框、圆角、背景色的标题容器,放在Card顶部居中位置,向上偏移标题自身高度的一半,做出跨在Card边框上的视觉效果 - 标题容器的背景色需要和Card背景色保持一致,避免叠层位置透底
参考实现代码如下:
import 'package:flutter/material.dart'; class TitledOutlinedCard extends StatelessWidget { /// 卡片标题文字 final String cardTitle; /// 卡片内容区域 final Widget cardChild; const TitledOutlinedCard({ super.key, required this.cardTitle, required this.cardChild, }); @override Widget build(BuildContext context) { // 标题框固定高度,可根据需求自行调整 const double titleBoxHeight = 40; return Stack( clipBehavior: Clip.none, alignment: Alignment.topCenter, children: [ // 基础卡片主体 Card( elevation: 0, shape: const RoundedRectangleBorder( borderRadius: BorderRadius.all(Radius.circular(20)), side: BorderSide(color: Colors.black, width: 1), ), child: Padding( // 顶部内边距预留标题位置 padding: const EdgeInsets.only( top: titleBoxHeight / 2 + 16, left: 16, right: 16, bottom: 16, ), child: cardChild, ), ), // 突出式标题框 Positioned( top: -titleBoxHeight / 2, child: Container( height: titleBoxHeight, padding: const EdgeInsets.symmetric(horizontal: 24), alignment: Alignment.center, decoration: BoxDecoration( // 背景色和Card保持一致,避免透底 color: Colors.white, border: Border.all(color: Colors.black, width: 1), borderRadius: BorderRadius.circular(12), ), child: Text( cardTitle, style: const TextStyle(fontSize: 16, fontWeight: FontWeight.w500), ), ), ) ], ); } }
调试提示:如果需要给卡片加阴影,不要分别给Card和标题框单独设置elevation,否则会出现阴影断层,建议统一给Stack外层的容器加阴影效果即可;如果需要调整标题框的大小、圆角、配色,直接修改对应Container的属性就能匹配设计需求。
内容的提问来源于stack exchange,提问作者Tom
相关产品推荐
相关产品推荐

