Flutter中如何为TextFormField设置maxLength并将计数器置于输入框末尾?
实现TextFormField内部末尾显示字符计数器
要把字符计数器放到输入框内部末尾,你需要关闭默认的计数器,然后自定义一个计数器放在输入框的后缀位置,具体实现如下:
- 禁用TextFormField默认的下方计数器:通过
buildCounter参数返回null,关闭默认的底部计数器显示 - 在
InputDecoration的suffix属性中添加自定义计数器,实时展示当前输入长度和最大限制
修改后的完整代码:
child: TextFormField( controller: nameController, maxLength: 50, // 关闭默认计数器 buildCounter: (context, {required currentLength, required maxLength, required isFocused}) => null, decoration: InputDecoration( // 自定义计数器放在输入框内部末尾 suffix: Text( '${nameController.text.length}/50', style: TextStyle(fontSize: 12, color: Colors.grey), ), counterText: '', // 清空默认计数器占位文本 ), validator: (String? value) { if (value!.trim().isEmpty) { return 'error'; } return null; }, onSaved: (String? value) { name = value!.trim(); }, ),
如果是在StatefulWidget中使用,nameController.text.length会随输入内容自动更新,无需额外添加监听。你可以根据需求调整计数器的字体大小、颜色等样式,匹配你的UI设计。
内容的提问来源于stack exchange,提问作者John
相关产品推荐
相关产品推荐

