Flutter中使用CrossAxisAlignment无法让Card内Row居中的问题求助
解决Card内Row无法居中的问题
你当前的问题出在Row的mainAxisAlignment: MainAxisAlignment.spaceBetween属性上——这个配置会让Row的子组件在整个可用宽度范围内两端对齐、均匀分布,哪怕你用Center包裹Row,Row也会默认撑满Card的水平宽度,导致视觉上不是整体居中。
两种解决思路:
1. 直接让Row子组件整体居中
把Row的mainAxisAlignment改成MainAxisAlignment.center,这样三个Column会整体居中排列,也可以手动添加固定间距控制子组件间的距离:
Card( elevation: 4.0, // Card elevation child: Center( child: Padding( padding: EdgeInsets.all(16.0), // Padding inside the card child: Row( mainAxisAlignment: MainAxisAlignment.center, // 修改为center crossAxisAlignment: CrossAxisAlignment.center, children: <Widget>[ Column( children: <Widget>[ Text( 'Following', style: TextStyle( fontSize: 18.0, fontWeight: FontWeight.bold, ), ), Text( '5000', style: TextStyle( fontSize: 16.0, ), ), ], ), SizedBox(width: 40), // 手动添加固定间距 Column( children: <Widget>[ Text( 'Following', style: TextStyle( fontSize: 18.0, fontWeight: FontWeight.bold, ), ), Text( '5000', style: TextStyle( fontSize: 16.0, ), ), ], ), SizedBox(width: 40), Column( children: <Widget>[ Text( 'Following', style: TextStyle( fontSize: 18.0, fontWeight: FontWeight.bold, ), ), Text( '5000', style: TextStyle( fontSize: 16.0, ), ), ], ), ], ), ), ), )
2. 保持子组件间距同时整体居中
如果你想保留子组件之间的均匀间距,同时让整个Row在Card内居中,可以给Row加上mainAxisSize: MainAxisSize.min(让Row只占用子组件所需的最小宽度),再配合MainAxisAlignment.spaceBetween:
Card( elevation: 4.0, // Card elevation child: Center( child: Padding( padding: EdgeInsets.all(16.0), // Padding inside the card child: Row( mainAxisSize: MainAxisSize.min, // 添加这一行限制Row宽度 mainAxisAlignment: MainAxisAlignment.spaceBetween, crossAxisAlignment: CrossAxisAlignment.center, children: <Widget>[ Column( children: <Widget>[ Text( 'Following', style: TextStyle( fontSize: 18.0, fontWeight: FontWeight.bold, ), ), Text( '5000', style: TextStyle( fontSize: 16.0, ), ), ], ), Column( children: <Widget>[ Text( 'Following', style: TextStyle( fontSize: 18.0, fontWeight: FontWeight.bold, ), ), Text( '5000', style: TextStyle( fontSize: 16.0, ), ), ], ), Column( children: <Widget>[ Text( 'Following', style: TextStyle( fontSize: 18.0, fontWeight: FontWeight.bold, ), ), Text( '5000', style: TextStyle( fontSize: 16.0, ), ), ], ), ], ), ), ), )
这样Row不会撑满Card宽度,Center就能让它整体居中,同时子组件之间保持spaceBetween的均匀间距。
内容的提问来源于stack exchange,提问作者Saad
相关产品推荐
相关产品推荐

