新建一个类继承TextInputFormatter类,重写formatEditUpdate方法,代码如下:
import 'package:flutter/services.dart';
///输入框格式限制
class NumLengthInputFormatter extends TextInputFormatter {
///小数位数
int decimalLength;
///整数位数
int integerLength;
bool allowInputDecimal;
NumLengthInputFormatter({this.decimalLength = 2, this.integerLength = 4})
: 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),
);
}
}
使用如下:
TextField(
inputFormatters: [
NumLengthInputFormatter(decimalLength: 8, integerLength: 2),
],
),