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

Flutter TextFormField高度校验:如何在离开编辑时自动修正至100cm?

解决身高输入自动修正为最小值100cm的问题

原代码的问题分析

你当前的代码存在两个关键问题:

  1. 判断逻辑写反:原代码中if (int.parse(value) >= 100)会在身高≥100时把值设为100,完全违背需求;
  2. 变量操作无效:你修改的是局部变量value,并没有更新_heighController的文本内容,所以修正逻辑根本没生效。

另外,仅靠onFieldSubmitted只能处理回车提交的场景,无法覆盖点击页面其他地方失去焦点的情况,这也是需求没达成的原因之一。

正确实现方案

我们需要覆盖所有输入框失去编辑状态的场景(回车提交、点击外部失焦),同时修正逻辑判断,确保低于100的值自动改为100。

步骤1:提取统一的验证修正方法

先写一个单独的方法处理身高值的验证和修正,避免重复代码:

void _fixHeightValue() {
  final inputValue = _heighController.text.trim();
  if (inputValue.isEmpty) return;
  
  final height = int.tryParse(inputValue);
  if (height != null && height < 100) {
    setState(() {
      _heighController.text = '100';
    });
  }
}

这里用int.tryParse替代int.parse,避免输入非数字时抛出异常(虽然你的输入格式化器已经限制了数字,但做一层防护更稳妥)。

步骤2:更新TextFormField配置

在TextFormField中添加onFieldSubmitted和onFocusChanged回调,确保所有离开编辑的场景都触发修正:

TextFormField(
  onFieldSubmitted: (_) => _fixHeightValue(),
  onFocusChanged: (hasFocus) {
    if (!hasFocus) {
      _fixHeightValue();
    }
  },
  inputFormatters: [
    LengthLimitingTextInputFormatter(3),
    FilteringTextInputFormatter.allow(RegExp(r'^[1-9][0-9]*')),
  ],
  textAlign: TextAlign.center,
  keyboardType: TextInputType.number,
  style: const TextStyle(fontSize: 16, color: Colors.white),
  controller: _heighController,
  cursorColor: Colors.white,
  decoration: InputDecoration(
    hintText: "in cm",
    hintStyle: TextStyle(color: Colors.white)
  ),
),

效果说明

  • 输入90后按回车,输入框内容会自动变为100;
  • 输入90后点击页面其他区域,输入框失去焦点时也会自动改为100;
  • 输入≥100的值时,保持原输入不变。

内容的提问来源于stack exchange,提问作者Fabian M

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 12:40:38