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

Flutter中使用TextInputFormatter实现TextField输入大写异常求助

更新记录(2023/12/05)
  • 已通过设置keyboardType为TextInputType.visiblePassword解决此前问题。
  • 询问Stack Overflow上的问题《Flutter TextField value always uppercase & debounce》是否有新进展。
强制大写输入异常问题详情

为实现TextField输入内容强制转为大写,尝试了两种TextInputFormatter实现方式:

方式一

class UpperCaseTextFormatter extends TextInputFormatter {
  @override
  TextEditingValue formatEditUpdate(TextEditingValue oldValue, TextEditingValue newValue) {
    return TextEditingValue(
      text: newValue.text.toUpperCase(),
      selection: newValue.selection,
    );
  }
}

方式二

class UpperCaseTextFormatter extends TextInputFormatter {
  @override
  TextEditingValue formatEditUpdate(TextEditingValue oldValue, TextEditingValue newValue) {
    return newValue.copyWith(text: newValue.text.toUpperCase());
  }
}

使用上述任一方式时,输入"QWER"会出现异常,最终结果变为"QQWQWEQWER",对应的TextFormField代码如下:

TextFormField(
  controller: _controller,
  inputFormatters: [
    UpperCaseTextFormatter(),
  ],
  decoration: InputDecoration(
    border: OutlineInputBorder(),
  ),
),

需求说明:不希望使用textCapitalization,因为用户仍可手动将输入改为小写,需通过TextInputFormatter实现强制大写输入。

内容的提问来源于stack exchange,提问作者Jack Huang

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 07:52:20