Flutter中FormBuilderTextField添加prefixIcon下拉后labelText如何左对齐
问题描述
想要带国家码下拉的FormBuilderTextField标签和普通文本输入框的标签保持一致左对齐,因为加了前置下拉组件导致标签被挤到中间。
问题示意图

解决方案
标签偏移是因为InputDecoration的prefixIcon默认会占用前置空间,标签的默认渲染起始位置在prefixIcon右侧,所以被宽度120的下拉组件推到了中间。
只需要调整外层FormBuilderTextField的InputDecoration配置即可修复:
需新增的3个配置项
floatingLabelAlignment: FloatingLabelAlignment.start:强制输入框激活后上浮的标签靠左对齐prefixIconConstraints: BoxConstraints.tightFor(width: 120):明确prefixIcon的尺寸约束,避免框架自动计算布局时挤压标签位置alignLabelWithHint: true:让未激活状态下的标签也和输入文本保持相同的对齐规则,向左靠齐
完整修改后代码
Padding( padding: EdgeInsets.only(top: 8, bottom: 8), child: FormBuilderTextField( controller: controller, name: name!, initialValue: initialValue, style: TextStyle(color: Colors.black), enabled: enabled, keyboardType: keyBoardType, decoration: InputDecoration( // 新增以下3行配置 floatingLabelAlignment: FloatingLabelAlignment.start, prefixIconConstraints: BoxConstraints.tightFor(width: 120), alignLabelWithHint: true, prefixIcon: Container( width: 120.0, child: FormBuilderDropdown( name: "countryList", iconSize: 0.0, decoration: InputDecoration( icon: null, labelStyle: TextStyle( color: enabled ? Colors.black54 : Theme.of(context).disabledColor), contentPadding: EdgeInsets.all(8), enabledBorder: InputBorder.none, ), enabled: enabled, items: countries .map((Country country) => DropdownMenuItem( value: country.id, child: Row( children: [ CachedNetworkImage( width: 30, height: 20, imageUrl: country.photo!.path!, imageBuilder: (context, imageProvider) => Container( decoration: BoxDecoration( image: DecorationImage( image: imageProvider, fit: BoxFit.fill), ), ), placeholder: (context, url) => CircularProgressIndicator(), errorWidget: (context, url, error) => Icon(Icons.error), ), SizedBox( width: 10.0, ), Text("+${country.phoneCode}" ?? "") ], ), )) .toList(), ), ), labelText: label, labelStyle: TextStyle( color: enabled ? Colors.black54 : Theme.of(context).disabledColor), contentPadding: EdgeInsets.all(16), focusedBorder: OutlineInputBorder( borderSide: BorderSide(color: Theme.of(context).primaryColor), ), border: OutlineInputBorder(borderSide: BorderSide()), ), validator: validator, obscureText: obscureText!, ), );
内容的提问来源于stack exchange,提问作者Chatura Dilan
相关产品推荐
相关产品推荐

