Flutter中Stack组件定位问题:如何将头像置于Container中心?
将CircleAvatar定位到Container底部圆角的中心位置
你的当前代码:
Stack( children: [ Container( height: MediaQuery.of(context).size.height * 0.5, decoration: BoxDecoration( borderRadius: BorderRadius.only( bottomLeft: Radius.circular(100.0), bottomRight: Radius.circular(100.0)), color: darkBlue, ), ), Positioned( bottom: 0, left: MediaQuery.of(context).size.width / 3, child: CircleAvatar( backgroundColor: white, radius: 70, child: Image.asset('assets/images/homepage.png'))), ], )
问题:当前设置bottom: 0会让头像对齐Stack底部,需要将头像放置到图中黑色圆圈标注的Container底部圆角中心位置。
解决方案:
修改Positioned的定位参数,让头像中心精准对齐Container底部圆角的中心:
- 垂直方向:设置
bottom为负的头像半径,让头像中心对齐Container的底部边缘 - 水平方向:计算屏幕中点减去头像半径的位置,确保水平居中
修改后的代码:
Stack( children: [ Container( height: MediaQuery.of(context).size.height * 0.5, decoration: BoxDecoration( borderRadius: BorderRadius.only( bottomLeft: Radius.circular(100.0), bottomRight: Radius.circular(100.0)), color: darkBlue, ), ), Positioned( // 垂直偏移:让头像中心落在Container底部边缘 bottom: -70, // 水平偏移:让头像中心与屏幕中点对齐 left: MediaQuery.of(context).size.width / 2 - 70, child: CircleAvatar( backgroundColor: white, radius: 70, child: Image.asset('assets/images/homepage.png'))), ], )
说明:
bottom: -70:CircleAvatar半径为70,负的bottom值会让头像向上偏移70,刚好让中心落在Container的底部边缘(即圆角中心)left: MediaQuery.of(context).size.width / 2 -70:屏幕宽度的一半减去头像半径,确保头像水平中心与Container底部圆角的中心完全重合
内容的提问来源于stack exchange,提问作者ckot
相关产品推荐
相关产品推荐

