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

Flutter如何让TextField的label与输入文本在同一容器内居中对齐

你需要调整两处核心配置即可实现全部文本的垂直居中效果:

  1. 为TextField添加textAlignVertical: TextAlignVertical.center属性,强制输入内容、hint提示、label标签统一垂直居中对齐
  2. 将InputDecoration中的contentPadding设置为EdgeInsets.zero,清除TextField默认自带的上下内边距,避免和外层固定高度的Container产生布局冲突

修改后的完整代码如下:

Container(
  height: 60,
  padding: EdgeInsetsDirectional.only(
    start: width * 0.038,
    end: width * 0.038,
  ),
  decoration: BoxDecoration(
    border: Border.all(
        color: state.hasError
            ? Constant.errorColor
            : Constant.greyColor,
        width: 1),
    borderRadius: const BorderRadius.all(Radius.circular(10)),
  ),
  child: TextField(
    textAlignVertical: TextAlignVertical.center, // 新增垂直居中配置
    inputFormatters: inputFormatter,
    controller: controller,
    onSubmitted: onSubmitted,
    onChanged: state.didChange,
    focusNode: focusNode,
    textInputAction: textInputAction,
    keyboardType: keyboard,
    obscureText: obscure,
    decoration: InputDecoration(
      labelText: label,
      alignLabelWithHint: true,
      labelStyle: Constant.hintText.copyWith(
        color: state.hasError
            ? Constant.errorColor
            : Constant.greyColor,
        fontSize: 14,
      ),
      hintText: hint,
      hintStyle: Constant.hintText.copyWith(fontSize: 14),
      contentPadding: EdgeInsets.zero, // 修改内边距配置
      border: InputBorder.none,
      focusedBorder: InputBorder.none,
      enabledBorder: InputBorder.none,
      errorBorder: InputBorder.none,
      disabledBorder: InputBorder.none,
    ),
  ),
),

如果调整后仍有细微偏移,可适当调整contentPadding的vertical数值,比如设置为EdgeInsets.symmetric(vertical: 2)做微小校准即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 00:24:00