123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354 |
- import 'package:flutter/services.dart';
- /*
- 工具类
- * */
- // 限制小数位数
- class NumberTextInputFormatter extends TextInputFormatter {
- static const defaultDouble = 0.001;
- ///允许的小数位数,-1代表不限制位数
- int digit;
- NumberTextInputFormatter({this.digit = -1});
- static double strToFloat(String str, [double defaultValue = defaultDouble]) {
- try {
- return double.parse(str);
- } catch (e) {
- return defaultValue;
- }
- }
- ///获取目前的小数位数
- static int getValueDigit(String value) {
- if (value.contains(".")) {
- return value.split(".")[1].length;
- } else {
- return -1;
- }
- }
- @override
- TextEditingValue formatEditUpdate(TextEditingValue oldValue, TextEditingValue newValue) {
- // TODO: implement formatEditUpdate
- String value = newValue.text;
- int selectionIndex = newValue.selection.end;
- if (value == ".") {
- value = "0.";
- selectionIndex++;
- } else if(value=="-"){
- value = "-";
- selectionIndex++;
- }else if (value != "" &&
- value != defaultDouble.toString() &&
- strToFloat(value, defaultDouble) == defaultDouble ||
- getValueDigit(value) > digit) {
- value = oldValue.text;
- selectionIndex = oldValue.selection.end;
- }
- return new TextEditingValue(
- text: value,
- selection: new TextSelection.collapsed(offset: selectionIndex),
- );
- }
- }
|