Flutter开发:如何让Row内两个Container高度始终保持一致?
解决方案
要实现两个Container高度始终同步,只需调整Row的对齐方式并移除不必要的IntrinsicHeight,具体修改如下:
修改后的代码
ListView.builder( itemCount: 7, shrinkWrap: true, itemBuilder: (context, index) { return ListTile( title: Text( 'Day ${index + 1}', style: clientStyle(fontSize: xLSize, fontWeight: FontWeight.bold), ), subtitle: Row( // 添加这一行,强制子项拉伸至Row的最大高度 crossAxisAlignment: CrossAxisAlignment.stretch, children: [ Expanded( child: Container( padding: const EdgeInsets.all(10.0), decoration: BoxDecoration( color: fitishBlue.withOpacity(0.15), borderRadius: const BorderRadius.only( topLeft: Radius.circular(10.0), bottomLeft: Radius.circular(10.0), ), ), child: Text( 'Potato: 0g Rice: 0g Beans: 0g Milk: 0g Yogurt: 0g Cheese: 0g Cheese: 0g Cheese: 0g', style: clientStyle(fontSize: 18.0), ), ), ), Expanded( child: Container( padding: const EdgeInsets.all(10.0), decoration: BoxDecoration( color: fitishBlue.withOpacity(0.4), borderRadius: const BorderRadius.only( topRight: Radius.circular(10.0), bottomRight: Radius.circular(10.0), ), ), child: Text( 'Protein: 0g \nCarbs: 0g \nFats: 0g', style: clientStyle(fontSize: 18.0), ), ), ), ], ), ); }, )
原理说明
CrossAxisAlignment.stretch会让Row的所有子项高度强制匹配Row自身的高度,而Row的高度由其中内容最多的子项决定,因此两侧容器会自动同步高度。- 移除
IntrinsicHeight是因为它会限制Row的高度计算逻辑,反而可能导致子项高度无法充分拉伸。
内容的提问来源于stack exchange,提问作者Mohamed Rifay
相关产品推荐
相关产品推荐

