flutter 如何使TextField()上的范围数值抖动

uqjltbpv  于 2022-11-25  发布在  Flutter
关注(0)|答案(7)|浏览(165)

这是我的代码:

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。

hec6srdp

hec6srdp1#

当你键入一个数字然后删除它时,顶部向上投票的答案会表现出一些奇怪的行为(例如,如果你尝试键入一个新数字,它会停止工作)。
我做了一个稍微修改的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;
    }
  }
}
ybzsozfc

ybzsozfc2#

通过扩展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
)

希望这对你有帮助!

2g32fytz

2g32fytz3#

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

我希望这对你有帮助

b09cbbtk

b09cbbtk4#

您可以将onChanged替换为:

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

ojsjcaue5#

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
pjngdqdw

pjngdqdw6#

当文本更改时,可以使用clamp:

TextField(
  keyboardType: TextInputType.number,
  inputFormatters: [
    FilteringTextInputFormatter.digitsOnly,
  ],
  onChanged: (value) {
    final number = int.tryParse(value);
    if (number != null) {
      final text = number.clamp(min, max).toString();
      final selection = TextSelection.collapsed(
        offset: text.length,
      );
      textEditingController.value = TextEditingValue(
        text: text,
        selection: selection,
      );
    }
  },
)
jyztefdp

jyztefdp7#

有一个属性可用于最大长度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;
            },
          ),
        ),

相关问题