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

方法比较简单,新建一个类继承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),
        ],
      ),
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容