如何在校验提示前后保持TextFormField与DropdownButtonFormField对齐?
我已经在校验提示出现前成功对齐了TextFormField和DropdownButtonFormField,但校验提示出现后,两者的对齐出现了异常。
校验前效果:
校验后效果:
我清楚问题产生的原因,但尚未找到正确解决方案。以下是我的代码:
Row( crossAxisAlignment: CrossAxisAlignment.end, mainAxisSize: MainAxisSize.max, children: [ Expanded( child: TextFormField( decoration: const InputDecoration( contentPadding: EdgeInsets.all(6.0), label: Text("Quantity"), ), keyboardType: TextInputType.number, initialValue: "1", validator: (value) { if (value == null || value.isEmpty || int.tryParse(value) == null || int.tryParse(value)! <= 0) { return "Must be a valid positive number"; } else { return null; } }, onSaved: (value) { _enteredQuantity = int.parse(value!); }, ), ), const SizedBox( width: 8, ), Expanded( child: DropdownButtonFormField( hint: const Text("Category"), items: [ for (final category in categories.entries) DropdownMenuItem( value: category.value, child: Row( children: [ Icon(Icons.square, color: category.value.color), const SizedBox( width: 8, height: 8, ), Text(category.value.category), ], ), ), ], onChanged: (value) { if (value != null) { setState(() { _enteredCategory = value; }); } }, ), ) ], ),
解决方案
问题根源是TextFormField出现错误提示后高度增加,而DropdownButtonFormField没有预留错误提示区域,导致两者底部对齐时视觉错位。推荐两种解决方式:
给DropdownButtonFormField添加空错误提示占位
为DropdownButtonFormField的decoration设置空的errorText,让它保留错误提示的高度空间,确保和有错误提示的TextFormField高度一致:Expanded( child: DropdownButtonFormField( decoration: const InputDecoration(errorText: ''), // 添加此行 hint: const Text("Category"), // 其余代码保持不变 ), )用IntrinsicHeight强制控件等高
用IntrinsicHeight包裹Row,并将crossAxisAlignment改为CrossAxisAlignment.stretch,强制两个子控件高度完全一致:IntrinsicHeight( child: Row( crossAxisAlignment: CrossAxisAlignment.stretch, mainAxisSize: MainAxisSize.max, children: [ // 原有控件代码 ], ), )
第一种方法更贴合Material Design表单的原生样式,不会改变控件默认布局逻辑,优先推荐。
内容的提问来源于stack exchange,提问作者mkuzayez
相关产品推荐
相关产品推荐

