precision_limit_formatter.dart
2.01 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import 'package:flutter/services.dart';
import 'package:one_key/utils/utils.dart';
class PrecisionLimitFormatter extends TextInputFormatter {
int _scale;
PrecisionLimitFormatter(this._scale);
RegExp exp = RegExp(r"[0-9]");
static const String POINTER = ".";
static const String DOUBLE_ZERO = "00";
static const String ZERO = "0";
@override
TextEditingValue formatEditUpdate(
TextEditingValue oldValue, TextEditingValue newValue) {
print('oldValue:' + oldValue.text);
print('newValue:' + newValue.text);
if (newValue.text.startsWith('.')) {
return TextEditingValue(
text: '0.', selection: TextSelection.collapsed(offset: 2));
}
// if (newValue.text.startsWith(POINTER) && newValue.text.length == 1) {
// //第一个不能输入小数点
// return oldValue;
// }
///输入完全删除
if (newValue.text.isEmpty) {
return TextEditingValue();
}
///只允许输入小数
if (!exp.hasMatch(newValue.text)) {
Utils.showToast('只能输入数字!');
return oldValue;
}
if (newValue.text.startsWith(ZERO) &&
newValue.text.split("0")[1].startsWith(RegExp(r'[0-9]'))) {
return TextEditingValue(
text: '0', selection: TextSelection.collapsed(offset: 1));
// return newValue;
}
///包含小数点的情况
if (newValue.text.contains(POINTER)) {
///包含多个小数
if (newValue.text.indexOf(POINTER) !=
newValue.text.lastIndexOf(POINTER)) {
return oldValue;
}
String input = newValue.text;
int index = input.indexOf(POINTER);
///小数点后位数
int lengthAfterPointer = input.substring(index, input.length).length - 1;
///小数位大于精度
if (lengthAfterPointer > _scale) {
return oldValue;
}
} else if (newValue.text.startsWith(POINTER) ||
newValue.text.startsWith(DOUBLE_ZERO)) {
///不包含小数点,不能以“00”开头
return oldValue;
}
return newValue;
}
}