You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter中如何为TextFormField设置maxLength并将计数器置于输入框末尾?

实现TextFormField内部末尾显示字符计数器

要把字符计数器放到输入框内部末尾,你需要关闭默认的计数器,然后自定义一个计数器放在输入框的后缀位置,具体实现如下:

  1. 禁用TextFormField默认的下方计数器:通过buildCounter参数返回null,关闭默认的底部计数器显示
  2. 在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 11:05:19