Flutter表单校验导致同Row的TextFormField与IconButton对齐异常如何解决
修复方案
有两种常用的修复方式,优先推荐第一种:
方案1:使用TextFormField原生的suffixIcon属性(最优解)
TextFormField的InputDecoration自带suffixIcon配置,专门用来在输入框尾部放置图标,该图标会自动和输入框保持对齐,不会受错误提示的高度变化影响,同时也不需要额外嵌套Row布局。
修改后的代码如下:
TextFormField( key: Key('new_event_address'), autofocus: false, initialValue: widget.address, decoration: InputDecoration( hintText: "", contentPadding: EdgeInsets.fromLTRB(20.0, 10.0, 20.0, 10.0), border: OutlineInputBorder(borderRadius: BorderRadius.circular(5.0)), focusedBorder: OutlineInputBorder( borderSide: const BorderSide(color: Colors.black26, width: 2.0), borderRadius: BorderRadius.circular(5.0), ), // 直接把IconButton放在suffixIcon属性中 suffixIcon: Padding( padding: EdgeInsets.only(right: 5), child: IconButton( icon: const Icon(Icons.add_location_outlined), onPressed: () {}, ), ), ), onSaved: (value) => setState(() => _address = value), validator: (val) => val.length == 0 ? CustomResources.strings["add_event_validation_address_required"] : null, )
方案2:保留原有Row结构,调整对齐规则
如果需要保留自定义Row的布局结构,只需要给Row设置交叉轴顶部对齐,让IconButton和TextFormField的顶部保持对齐,不受下方错误文本的高度影响即可:
Row( // 新增该行,设置交叉轴顶部对齐 crossAxisAlignment: CrossAxisAlignment.start, children: [ Expanded( child: TextFormField( key: Key('new_event_address'), autofocus: false, initialValue: widget.address, decoration: InputDecoration( hintText: "", contentPadding: EdgeInsets.fromLTRB(20.0, 10.0, 20.0, 10.0), border: OutlineInputBorder(borderRadius: BorderRadius.circular(5.0)), focusedBorder: OutlineInputBorder( borderSide: const BorderSide(color: Colors.black26, width: 2.0), borderRadius: BorderRadius.circular(5.0), ), ), onSaved: (value) => setState(() => _address = value), validator: (val) => val.length == 0 ? CustomResources.strings["add_event_validation_address_required"] : null, ), ), Padding(padding: EdgeInsets.only(right: 5)), // 可根据实际展示效果微调顶部padding,让图标和输入框内容垂直居中 Padding( padding: EdgeInsets.only(top: 4), child: IconButton( icon: const Icon(Icons.add_location_outlined), onPressed: () {}, ), ) ], )
内容的提问来源于stack exchange,提问作者user1209216
相关产品推荐
相关产品推荐

