如何在Flutter中实现自定义标签位置的TextFormField输入框
实现方案
推荐直接使用Flutter输入框原生的prefix/prefixText属性实现,完全不需要自定义Stack监听状态,属于输入框原生装饰的一部分,所有原有输入框功能都可以正常使用:
方案1:简单文本Label用prefixText
直接将原来的labelText替换为prefixText即可,Label会固定在输入框左侧,不会随输入/焦点状态上浮到边框顶部:
TextFormField( decoration: InputDecoration( // 固定左侧Label文本,末尾加空格可以和输入内容留出间距 prefixText: "Label ", // 自定义Label的字体颜色、大小等样式 prefixStyle: const TextStyle( color: Colors.grey, fontSize: 14, ), border: OutlineInputBorder( borderRadius: BorderRadius.all( Radius.circular(getPt(4)), ), ), // 调整内边距保证内容垂直居中,可根据实际需求修改数值 contentPadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 14), ), );
方案2:复杂样式Label用prefix
如果Label需要搭配图标、自定义间距等更复杂的布局,可以用prefix属性传入自定义Widget:
TextFormField( decoration: InputDecoration( prefix: Row( // 保证Row只占用必要宽度,不会把输入内容挤到最右侧 mainAxisSize: MainAxisSize.min, children: const [ // 可自定义添加图标、间距等内容 SizedBox(width: 8), Text("Label", style: TextStyle(color: Colors.grey, fontSize: 14)), SizedBox(width: 8), ], ), border: OutlineInputBorder( borderRadius: BorderRadius.all( Radius.circular(getPt(4)), ), ), contentPadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 14), ), );
以上两种方案点击Label区域都会自动触发输入框聚焦,不需要额外处理事件监听,也不会破坏输入框原有布局。
内容的提问来源于stack exchange,提问作者3squad
相关产品推荐
相关产品推荐

