TextField的suffix属性无法将CustomDropDownBtn放在输入框右侧如何解决?
问题原因
Flutter的InputDecoration中suffix、suffixIcon属性默认带有父级尺寸约束,未明确指定宽高的自定义组件会被约束挤压导致无法正常显示,这是系统内置Icon能正常显示、你自定义组件无法显示的核心原因。
解决方案
不需要硬加内边距调整,按以下步骤操作即可:
- 方案1:给自定义组件明确尺寸约束
在你的suffixWidget外层套SizedBox指定宽高,匹配你自定义组件的实际尺寸即可:
suffix: showSuffixWidget ? SizedBox( width: 80, // 按需调整为你自定义下拉按钮的实际宽度 height: 32, // 按需调整为你自定义下拉按钮的实际高度 child: suffixWidget, ) : null,
- 方案2:调整输入框内边距预留显示空间
如果指定尺寸后组件显示被截断,可通过contentPadding给输入框右侧预留足够的空间,配合isDense参数取消默认冗余留白:
TextField( decoration: InputDecoration( filled: true, fillColor: kTextFieldBgColor, // 新增这两个参数 isDense: true, contentPadding: EdgeInsets.fromLTRB(12, 12, 92, 12), // 右侧padding数值比suffix宽度大10-12即可,留出间隙 enabledBorder: UnderlineInputBorder( borderRadius: BorderRadius.all(Radius.circular(12.0)), borderSide: BorderSide(style: BorderStyle.none), ), suffix: showSuffixWidget ? SizedBox( width: 80, height: 32, child: suffixWidget, ) : null, focusedBorder: UnderlineInputBorder( borderRadius: BorderRadius.all(Radius.circular(12.0)), borderSide: BorderSide(style: BorderStyle.none), ), ), )
- 方案3:固定右侧组件可改用suffixIcon
如果你需要自定义组件固定在输入框右侧,不跟随输入内容滚动,直接用suffixIcon属性配合尺寸约束即可,和suffix用法完全一致。
内容的提问来源于stack exchange,提问作者Sulabh Shrestha
相关产品推荐
相关产品推荐

