Flutter中Row使用crossAxisAlignment对齐部件时右侧溢出如何解决
问题原因
- AppBar 的
leading属性默认有固定宽度限制(默认值为56dp),你在leading中放置的头像+文本的布局总宽度超出了这个限制,所以会出现右侧溢出报错,也无法实现预期的布局效果。 - 你写在 Row 里的
CrossAxisAlignment.center是让子元素在垂直方向居中对齐(Row的主轴是横向,交叉轴是纵向),你搭配 Column 的mainAxisAlignment: MainAxisAlignment.start使用,会导致文本内容靠上显示,和头像无法垂直对齐。
修复方案
不需要使用 leading 放置自定义布局,直接把你的自定义头部布局放到 AppBar 的 title 属性中即可,修改后的代码如下:
Scaffold( appBar: AppBar( elevation: 0.0, backgroundColor: Colors.transparent, // 取消默认leading的占位 leading: const SizedBox.shrink(), // 自定义title布局 title: Row( crossAxisAlignment: CrossAxisAlignment.center, mainAxisSize: MainAxisSize.min, children: [ Container( height: 40, width: 40, decoration: const BoxDecoration( color: Colors.grey, shape: BoxShape.circle, ), ), // 头像和文本之间加间距 const SizedBox(width: 8), Column( crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.center, children: const [ Text( "Welcome", style: TextStyle( fontSize: 10, fontWeight: FontWeight.normal, color: Colors.grey, ), ), Text( "John", style: TextStyle( fontSize: 12, fontWeight: FontWeight.bold, color: Colors.black, ), ), ], ), ], ), actions: [ IconButton( onPressed: () {}, icon: const Icon(Icons.search), color: Colors.black, ) ], ), );
内容的提问来源于stack exchange,提问作者dev1ce
相关产品推荐
相关产品推荐

