Flutter行列布局问题:无法为Job id与011设置间距
解决Flutter内层Row子元素无间距的问题
你遇到的问题很典型——明明给内层Row设置了MainAxisAlignment.spaceBetween,但"Job id"和"011"还是紧挨在一起,核心原因是这个内层Row没有足够的宽度来发挥spaceBetween的作用:它的父组件Column设置了crossAxisAlignment: CrossAxisAlignment.start,这会让Row的宽度仅包裹自身子元素的总宽度,自然没法拉开两个文本的距离。
下面给你两种实用的解决方案,按需选择即可:
方案1:让Row占满可用宽度,实现两端对齐
给内层Row外面套一个Expanded,让它占满Column的可用宽度,这样MainAxisAlignment.spaceBetween就能把两个Text分别推到左右两端:
Row( mainAxisSize: MainAxisSize.max, crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Container( margin: EdgeInsets.only(right: 10.0), width: 50.0, height: 50.0, decoration: BoxDecoration( shape: BoxShape.circle, image: DecorationImage( fit: BoxFit.fill, image: AssetImage('assets/noimage.jpg'), ), ), ), Column( mainAxisSize: MainAxisSize.max, crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: <Widget>[ Expanded( // 新增Expanded让Row占满宽度 child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: <Widget>[ Text( 'Job id', style: TextStyle( color: Colors.grey.shade700, fontSize: 16.0, fontWeight: FontWeight.normal, ), ), Text( '011', style: TextStyle( color: Colors.grey.shade700, fontSize: 16.0, fontWeight: FontWeight.normal, ), ), ], ), ), ], ), ], )
方案2:添加固定间距(适合小间距场景)
如果不需要两端对齐,只是想给两个文本加个固定空隙,直接在两个Text之间插入SizedBox即可,这种方式简单直观:
Row( mainAxisSize: MainAxisSize.max, crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Container( margin: EdgeInsets.only(right: 10.0), width: 50.0, height: 50.0, decoration: BoxDecoration( shape: BoxShape.circle, image: DecorationImage( fit: BoxFit.fill, image: AssetImage('assets/noimage.jpg'), ), ), ), Column( mainAxisSize: MainAxisSize.max, crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: <Widget>[ Row( children: <Widget>[ Text( 'Job id', style: TextStyle( color: Colors.grey.shade700, fontSize: 16.0, fontWeight: FontWeight.normal, ), ), SizedBox(width: 8.0), // 新增固定宽度的间距 Text( '011', style: TextStyle( color: Colors.grey.shade700, fontSize: 16.0, fontWeight: FontWeight.normal, ), ), ], ), ], ), ], )
如果需要文本分别靠左右两端,选方案1;如果只需要简单的空隙,方案2更省事。
内容的提问来源于stack exchange,提问作者Urvashi kharecha
相关产品推荐
相关产品推荐

