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

Flutter中如何限制TextFormField仅允许输入1-10范围内的数字

实现方法

你可以通过两种方式实现1-10的数值范围限制:

方式1:校验阶段拦截(提交时提示)

直接修改原有validator逻辑,增加数值范围判断即可,代码修改如下:

TextFormField(
  validator: (value) {
    if (value?.isEmpty ?? true) {
      return 'Please enter the Overall Rating';
    }
    // 解析输入值为整数,判断范围
    final inputNum = int.tryParse(value!);
    if (inputNum == null || inputNum < 1 || inputNum > 10) {
      return '请输入1-10范围内的有效数字';
    }
    return null;
  },
  keyboardType: TextInputType.number,
  inputFormatters: <TextInputFormatter>[
    FilteringTextInputFormatter.digitsOnly
  ],
  maxLength: 2,
  maxLengthEnforced: true,
  controller: overall,
  decoration: InputDecoration(
    hintText: "Overall Rating  Out of /10",
  ),
),

这种方式实现最简单,用户输入超出范围的值时,提交表单会触发校验提示。

方式2:输入阶段拦截(输入时直接限制非法值无法输入)

自定义TextInputFormatter,在用户输入过程中就直接拦截超出范围的内容,用户根本无法输入不符合要求的值:

  1. 先定义自定义输入格式化类
class RangeInputFormatter extends TextInputFormatter {
  final int min;
  final int max;

  RangeInputFormatter({required this.min, required this.max});

  @override
  TextEditingValue formatEditUpdate(TextEditingValue oldValue, TextEditingValue newValue) {
    // 允许空值,用于用户删除输入内容的场景
    if (newValue.text.isEmpty) {
      return newValue;
    }
    final inputValue = int.tryParse(newValue.text);
    // 输入内容不是有效数字、或者超出范围就返回上一次的合法值
    if (inputValue == null || inputValue < min || inputValue > max) {
      return oldValue;
    }
    return newValue;
  }
}
  1. 将自定义格式化类加入inputFormatters列表
inputFormatters: <TextInputFormatter>[
  FilteringTextInputFormatter.digitsOnly,
  // 限制范围1-10
  RangeInputFormatter(min: 1, max: 10),
],

这种方式体验更好,用户输入过程中就不会出现非法值,不需要额外的校验提示。

内容的提问来源于stack exchange,提问作者Saaimah Patel

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 23:15:05