number_text_input_formatter.dart
1.39 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
import 'package:flutter/services.dart';
/// 数字、小数格式化(默认两位小数)
class UsNumberTextInputFormatter extends TextInputFormatter {
UsNumberTextInputFormatter({
this.digit = 2,
this.max = 1000000
});
/// 允许输入的小数位数,-1代表不限制位数
final int digit;
/// 允许输入的最大值
final double max;
static const double _kDefaultDouble = 0.001;
double _strToFloat(String str, [double defaultValue = _kDefaultDouble]) {
try {
return double.parse(str);
} catch (e) {
return defaultValue;
}
}
///获取目前的小数位数
int _getValueDigit(String value) {
if (value.contains('.')) {
return value.split('.')[1].length;
} else {
return -1;
}
}
@override
TextEditingValue formatEditUpdate(TextEditingValue oldValue, TextEditingValue newValue) {
String value = newValue.text;
int selectionIndex = newValue.selection.end;
if (value == '.') {
value = '0.';
selectionIndex++;
} else if (value != '' && value != _kDefaultDouble.toString() &&
_strToFloat(value) == _kDefaultDouble ||
_getValueDigit(value) > digit || _strToFloat(value) > max) {
value = oldValue.text;
selectionIndex = oldValue.selection.end;
}
return TextEditingValue(
text: value,
selection: TextSelection.collapsed(offset: selectionIndex),
);
}
}