美文网首页Flutter实战技巧
Flutter实战技巧之-TextField限制输入整数位数和小

Flutter实战技巧之-TextField限制输入整数位数和小

作者: 不会弹吉他的二郎腿 | 来源:发表于2020-12-22 17:57 被阅读0次

方法比较简单,新建一个类继承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),
        ],
      ),

相关文章

网友评论

    本文标题:Flutter实战技巧之-TextField限制输入整数位数和小

    本文链接:https://www.haomeiwen.com/subject/mfgsnktx.html