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

Flutter中TextField按下回车换行时文字上移问题如何解决?

Flutter TextField换行文字向上偏移解决方案

问题原因

TextField默认采用baseline垂直对齐规则,单行和多行内容切换时基准线位置变化,且未配置垂直对齐属性,导致换行时文字出现向上跳变的偏移问题。

修复方案

只需要对TextField做以下调整即可:

  • 给style属性设置固定height,统一单行、多行状态下的行高
  • 新增textAlignVertical: TextAlignVertical.center,强制文字始终垂直居中
  • 若外层Container设置了固定高度,可给InputDecoration增加contentPadding修正内边距,避免内容被挤压

问题复现效果

TextField换行文字上移复现效果

修改后完整代码

Container(
  child: TextField(
    textAlign: TextAlign.center,
    textAlignVertical: TextAlignVertical.center, // 新增垂直居中配置
    autofocus: true,
    style: TextStyle(
      height: 1.2, // 配置固定行高,可根据字体大小调整到合适值
    ),
    onChanged: (value) {
      setState(() {
        mainText = value;
      });
    },
    keyboardType: TextInputType.multiline,
    minLines: 1,
    maxLines: 10,
    decoration: InputDecoration(
      contentPadding: EdgeInsets.zero, // 可选:清除默认内边距,根据需要调整
      focusedBorder: InputBorder.none,
      enabledBorder: InputBorder.none,
      hintText: "짧은 글귀를 집필해주세요",
      hintStyle: TextStyle(fontSize: 14, color: Colors.black),
    ),
  ),
)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.11 21:15:03