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

Flutter中如何实现TextFormField居中?附代码示例

Flutter TextFormField 居中显示实现

要让TextFormField组件整体在父容器中居中,可在现有代码的外层添加Center组件,修改后代码如下:

Padding(
  padding: const EdgeInsets.all(8.0),
  child: Center(
    child: SizedBox(
      width: 120,
      child: TextFormField(
        inputFormatters: [
          LengthLimitingTextInputFormatter(3),
        ],
        textAlign: TextAlign.center,
        keyboardType: TextInputType.number,
        style: const TextStyle(
          fontSize: 16,
        ),
        autovalidateMode: AutovalidateMode.disabled,
        controller: controller,
        cursorColor: Colors.white,
        decoration: InputDecoration(
          alignLabelWithHint: true,
          floatingLabelAlignment: FloatingLabelAlignment.center,
          labelText: lableText,
          labelStyle: const TextStyle(fontSize: 16)
        ),
      ),
    ),
  ),
)

核心调整说明:

  • 新增Center组件:使包含TextFormField的SizedBox在父布局中水平居中
  • 保留textAlign: TextAlign.center:确保输入框内的文本内容居中
  • 保留floatingLabelAlignment: FloatingLabelAlignment.center:让浮动状态的标签保持居中

若父布局为Row/Column,也可通过设置mainAxisAlignment: MainAxisAlignment.center、crossAxisAlignment: CrossAxisAlignment.center来实现整体居中。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 20:27:49