Flutter TextField小数位数精度限制

2019-07-28  本文已影响0人  刺客的幻影

直接上源码

import 'package:flutter/services.dart';

///价格输入框和数量输入框的限制
class PrecisionLimitFormatter extends TextInputFormatter {
  int _scale;

  PrecisionLimitFormatter(this._scale);

  RegExp exp = new RegExp("[0-9.]");
  static const String POINTER = ".";
  static const String DOUBLE_ZERO = "00";

  @override
  TextEditingValue formatEditUpdate(
      TextEditingValue oldValue, TextEditingValue newValue) {
    ///输入完全删除
    if (newValue.text.isEmpty) {
      return TextEditingValue();
    }

    ///只允许输入小数
    if (!exp.hasMatch(newValue.text)) {
      return oldValue;
    }

    ///包含小数点的情况
    if (newValue.text.contains(POINTER)) {
      ///包含多个小数
      if (newValue.text.indexOf(POINTER) !=
          newValue.text.lastIndexOf(POINTER)) {
        return oldValue;
      }
      String input = newValue.text;
      int index = input.indexOf(POINTER);

      ///小数点后位数
      int lengthAfterPointer = input.substring(index, input.length).length - 1;

      ///小数位大于精度
      if (lengthAfterPointer > _scale) {
        return oldValue;
      }
    } else if (newValue.text.startsWith(POINTER) ||
        newValue.text.startsWith(DOUBLE_ZERO)) {
      ///不包含小数点,不能以“00”开头
      return oldValue;
    }
    return newValue;
  }
}

使用方式


class FormatterTest extends StatelessWidget {
 final int _precision = 6;

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Container(
        child: TextField(
          inputFormatters: [PrecisionLimitFormatter(_precision)],
          keyboardType: TextInputType.numberWithOptions(),
          onChanged: (v) {},
        ),
      ),
    );
  }
}
上一篇下一篇

猜你喜欢

热点阅读