Flutter如何让TextField的label与输入文本在同一容器内居中对齐
你需要调整两处核心配置即可实现全部文本的垂直居中效果:
- 为TextField添加
textAlignVertical: TextAlignVertical.center属性,强制输入内容、hint提示、label标签统一垂直居中对齐 - 将InputDecoration中的contentPadding设置为
EdgeInsets.zero,清除TextField默认自带的上下内边距,避免和外层固定高度的Container产生布局冲突
修改后的完整代码如下:
Container( height: 60, padding: EdgeInsetsDirectional.only( start: width * 0.038, end: width * 0.038, ), decoration: BoxDecoration( border: Border.all( color: state.hasError ? Constant.errorColor : Constant.greyColor, width: 1), borderRadius: const BorderRadius.all(Radius.circular(10)), ), child: TextField( textAlignVertical: TextAlignVertical.center, // 新增垂直居中配置 inputFormatters: inputFormatter, controller: controller, onSubmitted: onSubmitted, onChanged: state.didChange, focusNode: focusNode, textInputAction: textInputAction, keyboardType: keyboard, obscureText: obscure, decoration: InputDecoration( labelText: label, alignLabelWithHint: true, labelStyle: Constant.hintText.copyWith( color: state.hasError ? Constant.errorColor : Constant.greyColor, fontSize: 14, ), hintText: hint, hintStyle: Constant.hintText.copyWith(fontSize: 14), contentPadding: EdgeInsets.zero, // 修改内边距配置 border: InputBorder.none, focusedBorder: InputBorder.none, enabledBorder: InputBorder.none, errorBorder: InputBorder.none, disabledBorder: InputBorder.none, ), ), ),
如果调整后仍有细微偏移,可适当调整contentPadding的vertical数值,比如设置为EdgeInsets.symmetric(vertical: 2)做微小校准即可。
内容的提问来源于stack exchange,提问作者Pigeon
相关产品推荐
相关产品推荐

