You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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
                 )
             ),
        ),
    ),
);

实际效果

TextField文本居底效果

解决方法

  • 给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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 04:05:21