Flutter如何调整TextButton高度匹配子Text以实现横向对齐
出现该问题的核心原因是Flutter Material库的TextButton默认自带最小尺寸约束、内边距,整体占用宽度远大于内部文本的宽度,超出Wrap单行可容纳宽度后就会自动换行。你可以通过以下两种方案实现横向对齐效果:
方案1:保留Wrap组件,移除TextButton默认约束
适合需要支持文本超长自动换行的场景,给TextButton加上样式配置清除默认约束,同时给Wrap设置交叉轴对齐保证垂直方向居中:
Wrap( crossAxisAlignment: WrapCrossAlignment.center, children: [ Text( "Forgot password?", style: GoogleFonts.poppins( color: Colors.white, fontSize: 16.0, ), ), TextButton( // 清除按钮默认的尺寸和内边距约束 style: TextButton.styleFrom( minimumSize: Size.zero, padding: EdgeInsets.zero, tapTargetSize: MaterialTapTargetSize.shrinkWrap, ), onPressed: () {}, child: Text( "Click here", style: GoogleFonts.poppins( color: Colors.white, fontSize: 16.0, decoration: TextDecoration.underline, ), ), ), ], )
方案2:使用Row组件实现精准对齐
如果确定文本总长度不会超出屏幕宽度,用Row可以实现更精准的文本对齐效果,支持按文本基线对齐避免两个文本出现高低差:
Row( mainAxisSize: MainAxisSize.min, // 按文本基线对齐,保证两个文本高度完全一致 crossAxisAlignment: CrossAxisAlignment.baseline, textBaseline: TextBaseline.alphabetic, children: [ Text( "Forgot password?", style: GoogleFonts.poppins( color: Colors.white, fontSize: 16.0, ), ), // 可根据需求调整两个元素的间距 SizedBox(width: 4), TextButton( style: TextButton.styleFrom( minimumSize: Size.zero, padding: EdgeInsets.zero, tapTargetSize: MaterialTapTargetSize.shrinkWrap, ), onPressed: () {}, child: Text( "Click here", style: GoogleFonts.poppins( color: Colors.white, fontSize: 16.0, decoration: TextDecoration.underline, ), ), ), ], )
内容的提问来源于stack exchange,提问作者Siddhant Saxena
相关产品推荐
相关产品推荐

