import 'package:flutter/services.dart'; import 'dart:math' as math; class InputFormat extends TextInputFormatter { InputFormat({this.decimalRange = 2}) : assert(decimalRange == null || decimalRange > 0); final int decimalRange; @override TextEditingValue formatEditUpdate(TextEditingValue oldValue, TextEditingValue newValue) { // 拿到錄入后的字符 String nValue = newValue.text; //當前所選擇的文字區域 TextSelection nSelection = newValue.selection; // 先來一波過濾,過濾出數字及小數點 // 匹配包含數字和小數點的字符 Pattern p = RegExp(r'(\d+\.?)|(\.?\d+)|(\.?)'); nValue = p.allMatches(nValue) .map<String>((Match match) => match.group(0)) .join(); // 用匹配完的字符判斷 if (nValue.startsWith('.')) { //如果小數點開頭,我們給他補個0 nValue = '0.'; } else if (nValue.contains('.')) { //來驗證小數點位置 if (nValue.substring(nValue.indexOf('.') + 1).length > decimalRange) { nValue = oldValue.text; } else { if (nValue.split('.').length > 2) { //多個小數點,去掉后面的 List<String> split = nValue.split('.'); nValue = split[0] + '.' + split[1]; } } } //使光標定位到最后一個字符后面 nSelection = newValue.selection.copyWith( baseOffset: math.min(nValue.length, nValue.length + 1), extentOffset: math.min(nValue.length, nValue.length + 1), ); return TextEditingValue( text: nValue, selection: nSelection, composing: TextRange.empty ); } }
使用:
keyboardType: TextInputType.numberWithOptions(decimal: true), inputFormatters: [InputFormat()],