Flutter中TextField文本居中异常求助:文本始终偏底部
问题:TextField文本在Container内始终居底,无法垂直居中
我希望让TextField内的文本在Container中居中显示,但实际文本始终处于底部位置。
实现代码
Container( width: 250.yswx, padding: EdgeInsets.symmetric(horizontal: 5.yswx), child: Center( child: TextField( textAlignVertical: TextAlignVertical.center, textAlign: TextAlign.center, style: TextStyle( color: Colors.black, fontSize: 13.yswx ), cursorColor: Colors.black, decoration: InputDecoration( border: InputBorder.none, hintText: widget.placeHolder, hintStyle: TextStyle( color: Color(0xffbfbfbf), fontSize: 13.yswx ) ), ), ), );
实际效果

解决方法
- 给Container添加固定高度,同时调整TextField的内边距与对齐设置:
Container( width: 250.yswx, height: 40.yswx, // 设置固定高度 padding: EdgeInsets.symmetric(horizontal: 5.yswx), alignment: Alignment.center, // 直接给Container设置居中对齐 child: TextField( textAlignVertical: TextAlignVertical.center, textAlign: TextAlign.center, style: TextStyle( color: Colors.black, fontSize: 13.yswx ), cursorColor: Colors.black, decoration: InputDecoration( border: InputBorder.none, hintText: widget.placeHolder, hintStyle: TextStyle( color: Color(0xffbfbfbf), fontSize: 13.yswx ), contentPadding: EdgeInsets.zero // 移除默认内边距干扰 ), ), ); - 问题原因:TextField默认带有
contentPadding,且未固定高度的Container会让TextField按自身默认布局规则拉伸,导致文本偏下。添加固定高度+移除默认内边距+直接设置Container居中对齐,即可确保文本垂直居中。
内容的提问来源于stack exchange,提问作者Hamed
相关产品推荐
相关产品推荐

