IT评测·应用市场-qidao123.com技术社区

标题: Flutter自定义TextInputFormatter实现金额输入框,同时解决iOS数字键盘不能 [打印本页]

作者: 耶耶耶耶耶    时间: 2024-10-2 14:49
标题: Flutter自定义TextInputFormatter实现金额输入框,同时解决iOS数字键盘不能
一、实现的效果

二、金额输入框基本要求


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

   所以这个时候最好的解决办法是答应输入.、数字和,然后在动态的将,替换成.
  四、完整代码

  1. import 'package:flutter/services.dart';
  2. class AmountTextFieldFormatter extends FilteringTextInputFormatter {
  3.   final int digit;
  4.   final String _decimalComma = ',';
  5.   final String _decimalDot = '.';
  6.   String _oldText = '';
  7.   AmountTextFieldFormatter({
  8.     this.digit = 2,
  9.     bool allow = true,
  10.   }) : super(RegExp('[0-9.,]'), allow: allow);
  11.   @override
  12.   TextEditingValue formatEditUpdate(
  13.     TextEditingValue oldValue,
  14.     TextEditingValue newValue,
  15.   ) {
  16.     ///替换`,`为`.`
  17.     if (newValue.text.contains(_decimalComma)) {
  18.       newValue = newValue.copyWith(
  19.         text: newValue.text.replaceAll(_decimalComma, _decimalDot),
  20.       );
  21.     }
  22.     final handlerValue = super.formatEditUpdate(oldValue, newValue);
  23.     String value = handlerValue.text;
  24.     int selectionIndex = handlerValue.selection.end;
  25.     ///如果输入框内容为.直接将输入框赋值为0.
  26.     if (value == _decimalDot) {
  27.       value = '0.';
  28.       selectionIndex++;
  29.     }
  30.     if (_getValueDigit(value) > digit || _pointCount(value) > 1) {
  31.       value = _oldText;
  32.       selectionIndex = _oldText.length;
  33.     }
  34.     _oldText = value;
  35.     return TextEditingValue(
  36.       text: value,
  37.       selection: TextSelection.collapsed(offset: selectionIndex),
  38.     );
  39.   }
  40.   ///输入多个小数点的情况
  41.   int _pointCount(String value) {
  42.     int count = 0;
  43.     value.split('').forEach((e) {
  44.       if (e == _decimalDot) {
  45.         count++;
  46.       }
  47.     });
  48.     return count;
  49.   }
  50.   ///获取目前的小数位数
  51.   int _getValueDigit(String value) {
  52.     if (value.contains(_decimalDot)) {
  53.       return value.split(_decimalDot)[1].length;
  54.     } else {
  55.       return -1;
  56.     }
  57.   }
  58. }
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。




欢迎光临 IT评测·应用市场-qidao123.com技术社区 (https://dis.qidao123.com/) Powered by Discuz! X3.4