关键代码
keyboardType: TextInputType.number, inputFormatters: [ FilteringTextInputFormatter(RegExp("[0-9.]"), allow: true), MyNumberTextInputFormatter(digit: 2), ],
TextField完整代码
1 TextField( 2 controller: _money, 3 keyboardType: TextInputType.number, 4 inputFormatters: [ 5 FilteringTextInputFormatter(RegExp("[0-9.]"), allow: true), 6 MyNumberTextInputFormatter(digit: 2), 7 ], 8 textAlign: TextAlign.left, 9 style: TextStyle(fontSize: 25.sp), 10 decoration: InputDecoration( 11 border: InputBorder.none, 12 hintText: '本次最多可提现${alipayMsg['money']}元', 13 hintStyle: TextStyle(color: Color.fromRGBO(119, 119, 119, 1), height: 1), 14 ), 15 autofocus: false, 16 onChanged: (val) { 17 money = val; 18 }, 19 )
MyNumberTextInputFormatter完整代码
1 import 'package:flutter/services.dart'; 2 3 class MyNumberTextInputFormatter extends TextInputFormatter { 4 static const defaultDouble = 0.001; 5 6 ///允许的小数位数,-1代表不限制位数 7 int digit; 8 MyNumberTextInputFormatter({this.digit = -1}); 9 static double strToFloat(String str, [double defaultValue = defaultDouble]) { 10 try { 11 return double.parse(str); 12 } catch (e) { 13 return defaultValue; 14 } 15 } 16 17 ///获取目前的小数位数 18 static int getValueDigit(String value) { 19 if (value.contains(".")) { 20 return value.split(".")[1].length; 21 } else { 22 return -1; 23 } 24 } 25 26 @override 27 TextEditingValue formatEditUpdate(TextEditingValue oldValue, TextEditingValue newValue) { 28 String value = newValue.text; 29 int selectionIndex = newValue.selection.end; 30 if (value == ".") { 31 value = "0."; 32 selectionIndex++; 33 } else if (value == "-") { 34 value = "-"; 35 selectionIndex++; 36 } else if (value != "" && value != defaultDouble.toString() && strToFloat(value, defaultDouble) == defaultDouble || getValueDigit(value) > digit) { 37 value = oldValue.text; 38 selectionIndex = oldValue.selection.end; 39 } 40 return new TextEditingValue( 41 text: value, 42 selection: new TextSelection.collapsed(offset: selectionIndex), 43 ); 44 } 45 }