flutter - 如何在 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。
解决方案
当您输入一个数字然后删除它时,最高投票的答案会表现出一些奇怪的行为(例如,如果您尝试输入一个新数字,它就会停止工作)。
我做了一个稍微改变的 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;
}
}
}
推荐阅读
- javascript - 在 Javascript 类中声明和访问变量
- firebase - 从新的 firebase auth 模拟器中删除所有用户
- jenkins - 如何在詹金斯管道中创建新凭据
- python - Azure devops 管道缓存 python 依赖项
- python - Python pandas 数据框打印 ValueError:无法将字符串转换为浮点数:'1,971.25'
- javascript - 制作一个 for 循环来计算特定单元格,然后将结果写入行中的最后一个单元格
- angular - 如何在 http 请求 URL 中使用 Observable?
- r - 固定效应 plm 函数的负调整 R 平方
- javascript - Javascript中字段的特定正则表达式
- python - Python for 循环不会获取列表中的每个元素