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

Flutter中如何实现文本框内文本的垂直居中?

解决Flutter登录输入框文本偏上的问题

我看你遇到了登录界面输入框文本垂直偏上的问题,结合你提供的代码和效果对比,问题主要出在输入框的内边距设置和自定义字体的适配上,下面给你具体的解决办法:

问题原因分析

你的全局ThemeData里的inputDecorationTheme设置了对称的垂直内边距vertical: 10.0,但你用了自定义字体Product Sans,不同字体的基线位置、行高和Flutter默认输入框样式不匹配,就导致了文本偏上的情况。

解决方案

方案1:调整全局输入框内边距(推荐)

直接修改全局主题里的contentPadding,把垂直方向的内边距改成不对称的值,让文本向下偏移到居中位置。比如把上下内边距调整为16.0和12.0(可以根据实际效果微调):

inputDecorationTheme: InputDecorationTheme(
  // 替换原来的对称内边距,适配自定义字体
  contentPadding: EdgeInsets.fromLTRB(10.0, 16.0, 10.0, 12.0),
  border: OutlineInputBorder(
    gapPadding: 3.0,
    borderRadius: BorderRadius.circular(22.0),
  ),
),

方案2:单独给登录输入框设置内边距

如果不想影响其他页面的输入框样式,可以单独给这个TextFormField的decoration设置contentPadding,覆盖全局配置:

Padding(
  padding: const EdgeInsets.symmetric(vertical: 8.0),
  child: TextFormField(
    maxLines: 1,
    controller: controller,
    validator: (value) {
      if (value.isEmpty) {
        return 'Please enter username.';
      }
      return null;
    },
    decoration: InputDecoration(
      labelText: 'Username',
      // 单独设置内边距
      contentPadding: EdgeInsets.fromLTRB(10.0, 16.0, 10.0, 12.0),
      suffixIcon: IconButton(
        highlightColor: Colors.transparent,
        icon: Container(
          width: 36.0,
          child: Icon(Icons.clear),
        ),
        onPressed: () {
          controller.clear();
        },
        splashColor: Colors.transparent,
      ),
      prefixIcon: Icon(Icons.account_circle),
    ),
  ),
)

方案3:调整文本行高

如果上面的内边距调整效果不够理想,还可以给TextFormField添加style属性,调整文本的行高,让文本垂直居中:

TextFormField(
  style: TextStyle(height: 1.3), // 根据字体微调行高
  // ...其他属性
)

小提示

因为你用了自定义字体Product Sans,建议多测试几个contentPadding的数值,找到最贴合你理想效果的参数——不同字体的基线和行高差异会导致适配值不一样。

内容的提问来源于stack exchange,提问作者leodriesch

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 08:04:48