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

如何让带prefix前缀的Flutter TextFormField与普通TextFormField宽度一致

解决方案

你当前两个输入框尺寸不一致的核心原因是带前缀的输入框多了isDense: true配置,该属性会压缩输入框的垂直高度,无前缀的输入框没有该配置,导致高度基准不同。无需用Container包裹,通过统一输入框本身的装饰属性即可实现尺寸一致,且完全适配不同屏幕:

  • 统一两个InputDecoration的基础配置,要么两个都加isDense: true,要么两个都去掉该配置,保证基础高度基准一致
  • 给两个输入框设置相同的contentPadding,强制内边距统一,避免前缀/无前缀带来的内边距差异
  • 调整前缀约束参数,避免minHeight: 0导致前缀区域高度被随意压缩,可设置为和普通输入框图标高度匹配的固定值

原效果示意图:
输入框效果示意图

调整后的代码示例:

TextFormField(
  textInputAction: TextInputAction.next,
  controller: namaField,
  focusNode: _namaFocus,
  autovalidateMode: AutovalidateMode.always,
  decoration: const InputDecoration(
    border: OutlineInputBorder(),
    icon: Icon(Icons.person),
    labelText: 'Nama Lengkap',
    // 统一加isDense,和第二个输入框对齐
    isDense: true,
    // 统一设置contentPadding
    contentPadding: EdgeInsets.symmetric(vertical: 16, horizontal: 12),
  ),
  validator: (String? value) {
    if (value == null || value.isEmpty) {
      return 'Mohon Isikan Data';
    }
    return null;
  },
),
SizedBox(height: 5),
TextFormField(
  textInputAction: TextInputAction.done,
  autovalidateMode: AutovalidateMode.always,
  keyboardType: TextInputType.phone,
  controller: noHpField,
  focusNode: _noHpFocus,
  decoration: const InputDecoration(
    border: OutlineInputBorder(),
    isDense: true,
    // 统一设置相同的contentPadding
    contentPadding: EdgeInsets.symmetric(vertical: 16, horizontal: 12),
    prefixIcon: Padding(
      padding: EdgeInsets.symmetric(horizontal: 8, vertical: 14),
      child: Text("+62",
          style: TextStyle(
              fontSize: 16,
              fontWeight: FontWeight.bold)),
    ),
    prefixIconConstraints:
    BoxConstraints(minWidth: 42, minHeight: 48),
    icon: Icon(Icons.phone_android),
    labelText: 'No HP',
  ),
  validator: (String? value) {
    if (value == null || value.isEmpty) {
      return 'Mohon Isikan Data';
    }
    return null;
  },
),

你也可以根据自己的设计需求调整contentPadding和prefixIconConstraints的数值,只要两个输入框的基础装饰属性保持一致,尺寸就会完全匹配。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 13:15:01