方法比较简单,新建一个类继承**TextInputFormatter**类,重写**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'); //小数点前内容大于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), ); }}
使用 限制整数位数为8位,小数位数为2位
TextField( inputFormatters: [ NumLengthInputFormatter(decimalLength: 8, integerLength: 2) ],),