首页 > 解决方案 > 如何在 TextField() Flutter 上设置范围数值

问题描述

这是我的代码:

            Padding(
              padding: const EdgeInsets.only(left: 8.0),
              child: TextField(
                inputFormatters: [
                  LengthLimitingTextInputFormatter(2),
                  WhitelistingTextInputFormatter.digitsOnly,
                ],
                keyboardType: TextInputType.number,
                decoration: new InputDecoration(
                    icon: Icon(Icons.assessment),
                    hintText: "Nilai",
                    border: InputBorder.none),
                onChanged: (String str) {
                  nilai = str;
                },
              ),
            ),

如何使输入数字仅在 1 - 20 范围内?

我正在尝试使用

WhitelistingTextInputFormatter(RegExp("[1-20]")),

但是,因为这个 WhitelistingTextInputFormatter RegExp 类型是字符串,所以我仍然可以输入 22,因为那里允许 2。

标签: flutterdart

解决方案


当您输入一个数字然后删除它时,最高投票的答案会表现出一些奇怪的行为(例如,如果您尝试输入一个新数字,它就会停止工作)。

我做了一个稍微改变的 TextInputFormatter,让您指定最小值和最大值,并修复原始答案中的一些奇怪行为。

class NumericalRangeFormatter extends TextInputFormatter {
  final double min;
  final double max;

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

  @override
  TextEditingValue formatEditUpdate(
    TextEditingValue oldValue,
    TextEditingValue newValue,
  ) {

    if (newValue.text == '') {
      return newValue;
    } else if (int.parse(newValue.text) < min) {
      return TextEditingValue().copyWith(text: min.toStringAsFixed(2));
    } else {
      return int.parse(newValue.text) > max ? oldValue : newValue;
    }
  }
}

推荐阅读