【问题标题】:How to make range number value on TextField() Flutter如何在 TextField() Flutter 上设置范围数值
【发布时间】:2020-03-09 05:24:41
【问题描述】:

这是我的代码:

            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。

【问题讨论】:

  • 您可以在“OnChange”方法上使用自定义输入验证。

标签: flutter dart


【解决方案1】:

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

我做了一个稍微改变的 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;
    }
  }
}

【讨论】:

    【解决方案2】:

    您可以通过扩展TextInputFormatter 类然后实现formatEditUpdate() 方法来实现您自己的TextInputFormatter

    这是你的用例示例 -

    class CustomRangeTextInputFormatter extends TextInputFormatter {
    
      @override
      TextEditingValue formatEditUpdate(TextEditingValue oldValue,TextEditingValue newValue,) { 
        if(newValue.text == '')
          return TextEditingValue();
        else if(int.parse(newValue.text) < 1)
          return TextEditingValue().copyWith(text: '1');
    
        return int.parse(newValue.text) > 20 ? TextEditingValue().copyWith(text: '20') : newValue;
      }
    }
    

    您可以像这样将自定义格式化程序添加到TextField -

    TextField(
      inputFormatters: [
        WhitelistingTextInputFormatter.digitsOnly,
        CustomRangeTextInputFormatter(),
      ],
      // Rest of the TextField code
    )
    

    希望这会有所帮助!

    【讨论】:

    • 这对我来说只是一点点工作,它改变了光标位置,所以我添加了这一行 return int.parse(newValue.text) > 20 ? TextEditingValue(selection: TextSelection.collapsed(offset: max.toString().length),).copyWith(text: '20') : newValue;
    【解决方案3】:
    keyboardType:
       TextInputType.number,
      inputFormatters:[                        //only numeric keyboard.
        LengthLimitingTextInputFormatter(6),      //only 6 digit
        WhitelistingTextInputFormatter.digitsOnly
      ],
    

    希望对你有帮助

    【讨论】:

    • WhitelistingTextInputFormatter.digitsOnly 已弃用
    【解决方案4】:

    您可以将onChanged 替换为:

    onChanged: (String value) {
        try {
            if(int.parse(value) >= 1 && int.parse(value) <= 20) {
                nilai = value;
            }
        } catch (e) {}
    

    【讨论】:

    • 谢谢哥们,但这是为了结果,我认为我需要一些在打字时仍然有效的代码。
    • 那么我建议您在Form 中使用TextFormField,在validator 中指定您的自定义验证并将autovalidate 属性设置为true。如果您不喜欢自动验证。你可以设置一个TextEditingController 并添加一个监听器。
    【解决方案5】:
    int.parse(value.toString()) < rangoMinimo ? 'El valor debe de ser mayor o igual a ${rangoMinimo}' : int.parse(value.toString()) > rangoMaximo ? 'El valor debe de ser menor o igual a ${rangoMaximo}' : null : null
    

    【讨论】:

      【解决方案6】:

      有一个属性可用于最大长度maxLength: 20,,因此您可以使用它

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

      【讨论】:

      • 谢谢,但 maxLenght 与 LengthLimitingTextInputFormatter(2) 相等,这是长度而不是值范围
      猜你喜欢
      • 1970-01-01
      • 2019-06-11
      • 1970-01-01
      • 1970-01-01
      • 2021-12-21
      • 2020-01-18
      • 1970-01-01
      • 1970-01-01
      • 2013-10-14
      相关资源
      最近更新 更多