Allow only two decimal number in flutter input?

后端 未结 9 1296
误落风尘
误落风尘 2020-12-30 07:03

I want only two digits after decimal point in the flutter input.User can\'t add more than two digits after decimal point.

9条回答
  •  南笙
    南笙 (楼主)
    2020-12-30 07:21

    And avoiding non necessary zeros... Please debug this code.

    import 'dart:math' as math;
    
    import 'package:flutter/services.dart';
    
    class DecimalTextInputFormatter extends TextInputFormatter {
      DecimalTextInputFormatter({this.decimalRange, this.activatedNegativeValues})
          : assert(decimalRange == null || decimalRange >= 0,
                'DecimalTextInputFormatter declaretion error');
    
      final int decimalRange;
      final bool activatedNegativeValues;
    
      @override
      TextEditingValue formatEditUpdate(
        TextEditingValue oldValue, // unused.
        TextEditingValue newValue,
      ) {
        TextSelection newSelection = newValue.selection;
        String truncated = newValue.text;
    
        if (newValue.text.contains(' ')) {
          return oldValue;
        }
    
        if (newValue.text.isEmpty) {
          return newValue;
        } else if (double.tryParse(newValue.text) == null &&
            !(newValue.text.length == 1 &&
                (activatedNegativeValues == true ||
                    activatedNegativeValues == null) &&
                newValue.text == '-')) {
          return oldValue;
        }
    
        if (activatedNegativeValues == false &&
            double.tryParse(newValue.text) < 0) {
          return oldValue;
        }
    
        if ((double.tryParse(oldValue.text) == 0 && !newValue.text.contains('.'))) {
          if (newValue.text.length >= oldValue.text.length) {
            return oldValue;
          }
        }
    
        if (decimalRange != null) {
          String value = newValue.text;
    
          if (decimalRange == 0 && value.contains(".")) {
            truncated = oldValue.text;
            newSelection = oldValue.selection;
          }
    
          if (value.contains(".") &&
              value.substring(value.indexOf(".") + 1).length > decimalRange) {
            truncated = oldValue.text;
            newSelection = oldValue.selection;
          } else if (value == ".") {
            truncated = "0.";
    
            newSelection = newValue.selection.copyWith(
              baseOffset: math.min(truncated.length, truncated.length + 1),
              extentOffset: math.min(truncated.length, truncated.length + 1),
            );
          }
    
          return TextEditingValue(
            text: truncated,
            selection: newSelection,
            composing: TextRange.empty,
          );
        }
        return newValue;
      }
    }
    

提交回复
热议问题