这是我的代码:
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;
},
),
),
Run Code Online (Sandbox Code Playgroud)
如何让输入的数字只在1-20范围内?
我正在尝试使用
WhitelistingTextInputFormatter(RegExp("[1-20]")),
Run Code Online (Sandbox Code Playgroud)
但是,因为这个 WhitelistingTextInputFormatter RegExp 类型是字符串,所以我仍然可以输入 22,因为那里允许输入 2。
Joe*_*ler 17
当您输入一个数字然后将其删除时,获得最高支持的答案会表现出一些奇怪的行为(例如,如果您尝试输入新数字,它会停止工作)。
我做了一个稍微修改的 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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
您可以TextInputFormatter通过扩展TextInputFormatter类然后实现formatEditUpdate()方法来实现您自己的方法。
这是您的用例示例 -
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;
}
}
Run Code Online (Sandbox Code Playgroud)
您可以添加自定义格式化程序,例如TextField-
TextField(
inputFormatters: [
WhitelistingTextInputFormatter.digitsOnly,
CustomRangeTextInputFormatter(),
],
// Rest of the TextField code
)
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助!
您可以替换onChanged为:
onChanged: (String value) {\n try\xc2\xa0{\n if(int.parse(value) >= 1 && int.parse(value) <= 20) {\n nilai = value;\n }\n } catch (e) {}\nRun Code Online (Sandbox Code Playgroud)\n
| 归档时间: |
|
| 查看次数: |
18969 次 |
| 最近记录: |