简体   繁体   English

如何在 TextField() Flutter 上制作范围数值

[英]How to make range number value on TextField() Flutter

This is my code:这是我的代码:

            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;
                },
              ),
            ),

How to make the input number like only range 1 - 20?如何使输入数字仅在 1 - 20 范围内?

I'm try to using我正在尝试使用

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

but, because this WhitelistingTextInputFormatter RegExp type is string, then I can still type 22 because 2 is allowed there.但是,因为这个 WhitelistingTextInputFormatter RegExp 类型是字符串,所以我仍然可以输入 22,因为那里允许 2。

You can implement you own TextInputFormatter by extending the TextInputFormatter class and then implementing the formatEditUpdate() method.您可以通过扩展TextInputFormatter class 然后实现formatEditUpdate()方法来实现自己的TextInputFormatter

Here is an example for you use case -这是您的用例示例-

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;
  }
}

And you can add the custom formatter to the TextField like so -您可以像这样将自定义格式化程序添加到TextField -

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

Hope this helps!希望这可以帮助!

keyboardType:
   TextInputType.number,
  inputFormatters:[                        //only numeric keyboard.
    LengthLimitingTextInputFormatter(6),      //only 6 digit
    WhitelistingTextInputFormatter.digitsOnly
  ],

hope this will help you希望对你有帮助

The top upvoted answer exhibits some odd behavior when you type a number and then delete it (eg if you try typing in a new number it stops working).当您输入一个数字然后删除它时,最高投票的答案会表现出一些奇怪的行为(例如,如果您尝试输入一个新数字,它就会停止工作)。

I made a slightly altered TextInputFormatter that let's you specify the min and max and fixes some of the weird behaviors from the original answer.我做了一个稍微改变的 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;
    }
  }
}

You could replace onChanged by:您可以将onChanged替换为:

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

Solved解决了

this is may be for someone with the same problem with me, I make this condition这可能是针对与我有同样问题的人,我提出了这个条件

int lenght;
if (widget.nilai < 10){
  lenght = 1;
} else {
  lenght = 2;
}

and this和这个

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

by the way, widget.nilai is dynamic value from my database顺便说一句,widget.nilai 是我数据库中的动态值

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

There is a property available for Max length maxLength: 20, so you can use this Max length 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;
            },
          ),
        ),

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM