方法比較簡(jiǎn)單图呢,新建一個(gè)類(lèi)繼承TextInputFormatter類(lèi),重寫(xiě)formatEditUpdate方法
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');
//小數(shù)點(diǎn)前內(nèi)容大于integerLength
if (beforePoint.length > integerLength) {
value = oldValue.text;
selectionIndex = oldValue.selection.end;
} else
//小數(shù)點(diǎn)前內(nèi)容小于等于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),
);
}
}
使用 限制整數(shù)位數(shù)為8位骗随,小數(shù)位數(shù)為2位
TextField(
inputFormatters: [
NumLengthInputFormatter(decimalLength: 8, integerLength: 2),
],
),