NumLengthInputFormatter.dart
1.38 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
import 'package:flutter/services.dart';
class NumLengthInputFormatter extends TextInputFormatter {
int decimalLength;
int integerLength;
bool allowInputDecimal;
NumLengthInputFormatter({this.decimalLength = 2, this.integerLength = 8}) : super();
@override
TextEditingValue formatEditUpdate(TextEditingValue oldValue, TextEditingValue newValue) {
String value = newValue.text;
int selectionIndex = newValue.selection.end;
if (newValue.text.contains('.')) {
int pointIndex = newValue.text.indexOf('.');
String beforePoint = newValue.text.substring(0, pointIndex);
print('$beforePoint');
//小数点前内容大于integerLength
if (beforePoint.length > integerLength) {
value = oldValue.text;
selectionIndex = oldValue.selection.end;
} else
//小数点前内容小于等于integerLength
{
String afterPoint = newValue.text.substring(pointIndex + 1, newValue.text.length);
if (afterPoint.length > decimalLength) {
value = oldValue.text;
selectionIndex = oldValue.selection.end;
}
}
} else {
if (newValue.text.length > integerLength) {
value = oldValue.text;
selectionIndex = oldValue.selection.end;
}
}
return new TextEditingValue(
text: value,
selection: new TextSelection.collapsed(offset: selectionIndex),
);
}
}