Flutter中如何让Container内NetworkImage适配嵌套Card高度
问题根因
- 外层承载Card的Container固定高度为屏幕高度的20%,但承载图片的子Container硬编码了屏幕高度26%的高度值,子组件高度大于父容器约束,直接打破了父容器的高度限制,导致图片无法匹配Card高度
- 代码中Row已设置
crossAxisAlignment: CrossAxisAlignment.stretch,本可让Row内子组件自动撑满垂直方向高度,但硬编码的图片容器高度直接覆盖了该拉伸规则 - 代码Row的children列表中混入了
EdgeInsets.zero,),onPressed: () {这类语法冗余内容,会触发布局渲染异常 - 右侧文本Column未做宽度约束,长文本易溢出,进一步干扰父容器的高度约束计算
修复步骤
- 删除图片Container上硬编码的height属性,仅保留需要的固定宽度,让Row的stretch规则自动把图片容器高度拉满Card高度
- 给图片Container添加
clipBehavior: Clip.hardEdge,避免圆角裁切异常 - 清理代码中混入的冗余语法片段,将TextButton的padding、shape配置统一放到
style参数中 - 给右侧文本Column外层包裹
Expanded,约束文本区域宽度,避免内容溢出 - 图片保持
BoxFit.cover适配规则即可,无需使用BoxFit.fitHeight,cover会自动按比例缩放图片填满容器,不会出现拉伸变形
修正后代码
Container( height: MediaQuery.of(context).size.height * 0.20, child: Card( shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(15), ), elevation: 5, child: TextButton( style: TextButton.styleFrom( padding: EdgeInsets.zero, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(15), ), ), onPressed: () { Navigator.push( context, MaterialPageRoute(builder: (context) => ViewDonation(donation: donation)) ); }, child: Row( mainAxisAlignment: MainAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.stretch, children: [ Container( width: MediaQuery.of(context).size.height * 0.18, clipBehavior: Clip.hardEdge, decoration: BoxDecoration( borderRadius: BorderRadius.only( bottomLeft: Radius.circular(15), topLeft: Radius.circular(15), ), image: DecorationImage( image: NetworkImage("https://emedz.net/images/doctors/20210213_163233.jpg"), fit: BoxFit.cover, ), ), ), SizedBox(width: MediaQuery.of(context).size.width * 0.04), Expanded( child: Padding( padding: const EdgeInsets.symmetric(vertical: 8, horizontal: 4), child: Column( mainAxisAlignment: MainAxisAlignment.spaceBetween, crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( donation.title, style: TextStyle( fontSize: 14, fontWeight: FontWeight.bold, color: AppColor.primary, ), ), Text(donation.contact, style: TextStyle(fontSize: 10)), Text( 'Rs. ${donation.amountRequired}/-', style: TextStyle( fontSize: 10, color: AppColor.primary, ), ), Text( 'Required till: ${donation?.dueDate ?? ""}', style: TextStyle(fontSize: 10), ), ], ), ), ), ], ), ), ), )
补充说明:如果需要图片四个角都做圆角,直接给图片Container的BorderRadius配置四个15圆角即可,外层TextButton已做圆角裁切限制,图片不会超出Card边界。
内容的提问来源于stack exchange,提问作者Ijaz Ahmed
相关产品推荐
相关产品推荐

