Flutter自定义TextInputFormatter实现金额输入框,同时解决iOS数字键盘不能输入小数点的问题

一、实现的效果

二、金额输入框基本要求

  • 只能输入.数字
  • 小数点后只能有俩位
  • 小数点不能作为开头

三、在iOS设备上这里还有个坑,数字键盘上这个小数点会根据你手机设置的不同国家地区来决定显示是.还是, 如下

所以这个时候最好的解决办法是允许输入.数字,然后在动态的将,替换成.

四、完整代码

import 'package:flutter/services.dart';

class AmountTextFieldFormatter extends FilteringTextInputFormatter {
   
  final int digit;
  final String _decimalComma = ',';
  final String _decimalDot = '.';
  String _oldText = '';

  AmountTextFieldFormatter({
   
    this.digit = 2,
    bool allow = true,
  }) : super(RegExp('[0-9.,]'), allow: allow);

  
  TextEditingValue formatEditUpdate(
    TextEditingValue oldValue,
    TextEditingValue newValue,
  ) {
   
    ///替换`,`为`.`
    if (newValue.text.contains(_decimalComma)) {
   
      newValue = newValue.copyWith(
        text: newValue.text.replaceAll(_decimalComma, _decimalDot),
      );
    }
    final handlerValue = super.formatEditUpdate(oldValue, newValue);
    String value = handlerValue.text;
    int selectionIndex = handlerValue.selection.end;

    ///如果输入框内容为.直接将输入框赋值为0.
    if (value == _decimalDot) {
   
      value = '0.';
      selectionIndex++;
    }
    if (_getValueDigit(value) > digit || _pointCount(value) > 1) {
   
      value = _oldText;
      selectionIndex = _oldText.length;
    }
    _oldText = value;
    return TextEditingValue(
      text: value,
      selection: TextSelection.collapsed(offset: selectionIndex),
    );
  }

  ///输入多个小数点的情况
  int _pointCount(String value) {
   
    int count = 0;
    value.split('').forEach((e) {
   
      if (e == _decimalDot) {
   
        count++;
      }
    });
    return count;
  }

  ///获取目前的小数位数
  int _getValueDigit(String value) {
   
    if (value.contains(_decimalDot)) {
   
      return value.split(_decimalDot)[1].length;
    } else {
   
      return -1;
    }
  }
}

相关推荐

  1. Flutter定义TextInputFormatter实现金额输入

    2023-12-14 05:08:08       53 阅读
  2. 音视频实战--定义输入输出IO

    2023-12-14 05:08:08       43 阅读
  3. input输入禁止输入小数点方法

    2023-12-14 05:08:08       28 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2023-12-14 05:08:08       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2023-12-14 05:08:08       100 阅读
  3. 在Django里面运行非项目文件

    2023-12-14 05:08:08       82 阅读
  4. Python语言-面向对象

    2023-12-14 05:08:08       91 阅读

热门阅读

  1. vmware 使用scsi_id 获取ID返回空

    2023-12-14 05:08:08       63 阅读
  2. Flutter开发笔记 —— sqflite插件数据库应用

    2023-12-14 05:08:08       56 阅读
  3. GitHub入门命令介绍

    2023-12-14 05:08:08       61 阅读
  4. docker快速搭建mongodb的分片集群

    2023-12-14 05:08:08       59 阅读
  5. mapbox修改样式

    2023-12-14 05:08:08       78 阅读
  6. 虚拟机元空间

    2023-12-14 05:08:08       61 阅读
  7. vscode编写markdown

    2023-12-14 05:08:08       67 阅读