Flutter 自定义高度卡片内Text组件文本溢出问题如何解决?
问题原因
- 布局约束冲突:外层卡片Container固定了144高度、104宽度,同时设置了左右各15、上下共25的内边距,内部Column的图片组件硬设了95高度,剩余给Text的高度仅为24,Column默认不会挤压子组件,文本达到2行时就会超出高度限制引发溢出。
- Text缺少截断配置:仅设置了
maxLines=2,但没有配置overflow属性,超出2行的文本不会自动截断,会继续绘制导致溢出。 - 图片宽度配置错误:内部图片Container硬设了104宽度,和外层卡片宽度一致,但外层卡片还有左右共30的内边距,图片本身已经出现横向溢出。
修复方案
按以下步骤修改代码即可解决:
- 用
Flexible包裹Text组件,让Text仅占用Column剩余的可用空间,不会超出高度限制 - 给Text增加
overflow: TextOverflow.ellipsis配置,超出2行的文本自动显示省略号截断 - 移除图片Container的硬编码宽度,设置适配属性让图片自适应父容器大小
修复后的核心代码
class ShopsCard extends StatelessWidget { final UniqueShop uniqueShop; ShopsCard({this.uniqueShop}); @override Widget build(BuildContext context) { return GestureDetector( onTap: (){ Navigator.push( context, MaterialPageRoute( builder: (context) => SearchScreen( searchArguments: SearchArguments( searchType: "campaign_shop_click", campaignShopSlug: uniqueShop.sellerShopSlug, searchDisplayName: uniqueShop.sellerShopBuisnessName), )), ); }, child: Container( height: 144, width: 104, margin: EdgeInsets.only(right: 8.0), decoration: BoxDecoration( color: Colors.white, borderRadius: BorderRadius.circular(10)), padding: EdgeInsets.only(left: 15.0, right: 15.0, top: 10, bottom: 15.0), child: Column( children: [ Container( height: 95.0, width: double.infinity, // 适配父容器宽度 child: uniqueShop.sellerShopImage != null ? populateNetworkImage(imgUrl: uniqueShop.sellerShopImage) : Icon( Icons.image, size: 50, )), if (uniqueShop.sellerShopBuisnessName != null) Flexible( // 新增Flexible包裹限制文本高度 child: Text( uniqueShop.sellerShopBuisnessName, maxLines: 2, overflow: TextOverflow.ellipsis, // 新增溢出截断配置 textAlign: TextAlign.center, style: commonDmSansTextStyle( fontSize: 12, fontWeight: FontWeight.w500, color: darkColor), ), ) ], ), ), ); } }
内容的提问来源于stack exchange,提问作者Yousuf Ali
相关产品推荐
相关产品推荐

