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

Flutter桌面应用:如何使第二行TextField与首行对应组件始终对齐

Flutter桌面应用TextField对齐问题解决

原代码中两行Row的元素flex比例不匹配,且元素的布局拟合模式不一致,导致窗口缩放时第二行的"New Second Weight" TextField无法和第一行的"New First Weight"保持对齐:

  • 第一行采用Expanded(flex:1)(Billing输入框) + Flexible(flex:5)(空白) + Expanded(flex:1)(New First Weight输入框)的结构,Expanded是强制占满可用空间的tight fit模式;
  • 第二行用Flexible(flex:2)(空白) + Flexible(flex:5)(文本) + Expanded(flex:1)(New Second Weight输入框),其中Flexible(flex:2)默认是loose fit模式,窗口缩放时宽度变化逻辑和第一行的两个Expanded总宽度不一致,导致右侧输入框偏移。

解决方法

统一两行的flex比例,让对应位置的元素flex值完全一致,同时保持布局拟合模式统一,还要同步第一行的margin设置:

body: Column(children: [
  const SizedBox(height: 15.0),
  Row(
    children: [
      // 第一部分:Billing输入框,flex:1
      Flexible(
        flex: 1,
        child: Container(
          margin: const EdgeInsets.fromLTRB(10, 0, 0, 0),
          color: Colors.white,
          height: 70,
          child: const TextField(
            decoration: InputDecoration(
              labelText: 'Billing',
              border: OutlineInputBorder(),
            ),
          ),
        ),
      ),
      // 中间空白区域,flex:5
      Flexible(
        flex: 5,
        child: Container(),
      ),
      // 第三部分:New First Weight输入框,flex:1
      Flexible(
        flex: 1,
        child: Container(
          margin: const EdgeInsets.fromLTRB(0, 0, 10, 0),
          color: Colors.white,
          height: 70,
          child: const TextField(
            decoration: InputDecoration(
              labelText: 'New First Weight',
              border: OutlineInputBorder(),
            ),
          ),
        ),
      ),
    ],
  ),
  const SizedBox(height: 2.0),
  Row(
    children: [
      // 对应第一行Billing输入框的位置,flex:1,同步左margin
      Flexible(
        flex: 1,
        child: Container(
          margin: const EdgeInsets.fromLTRB(10, 0, 0, 0),
        ),
      ),
      // 中间文本区域,flex:5
      Flexible(
        flex: 5,
        child: Container(
          color: Colors.white,
          height: 70,
          child: const Text(
              "First weight exists First weight exists First weight exists First weight exists First weight exists"),
        ),
      ),
      // 对应第一行New First Weight输入框的位置,flex:1,同步右margin
      Flexible(
        flex: 1,
        child: Container(
          margin: const EdgeInsets.fromLTRB(0, 0, 10, 0),
          color: Colors.white,
          height: 70,
          child: const TextField(
            decoration: InputDecoration(
              labelText: 'New Second Weight',
              border: OutlineInputBorder(),
            ),
          ),
        ),
      ),
    ],
  ),
]));

关键调整说明

  • 两行的三个区域flex比例统一为1:5:1,确保窗口缩放时各部分宽度变化比例完全一致;
  • 第二行第一个空白容器添加和第一行Billing输入框相同的左margin,避免整体布局偏移;
  • 全部使用Flexible(替换为Expanded效果一致),保证所有元素的布局拟合模式统一,宽度随窗口同步调整。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 22:35:07