TextFormField输入限制

本文介绍了一个自定义的Flutter输入框格式限制器类NumLengthInputFormatter,该类通过继承TextInputFormatter并重写formatEditUpdate方法实现对输入框的小数位数和整数位数进行限制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

新建一个类继承TextInputFormatter类,重写formatEditUpdate方法,代码如下:

import 'package:flutter/services.dart';

///输入框格式限制
class NumLengthInputFormatter extends TextInputFormatter {
  ///小数位数
  int decimalLength;
  ///整数位数
  int integerLength;
  bool allowInputDecimal;

  NumLengthInputFormatter({this.decimalLength = 2, this.integerLength = 4})
      : 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),
    );
  }
}

使用如下:

 TextField(
        inputFormatters: [
          NumLengthInputFormatter(decimalLength: 8, integerLength: 2),
        ],
      ),

感谢:https://www.jianshu.com/p/d0aaf3f33556

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值