Allow only two decimal number in flutter input?

后端 未结 9 1273
误落风尘
误落风尘 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:17

    The answer by @AjayKumar allows to limit text input to required decimal places.But my requirement was to avoid another character from keyboard except the number and a dot.So, I updated @AjayKumar's above answer

    import 'package:flutter/services.dart';
    import 'dart:math' as math;   
    
    class DecimalTextInputFormatter extends TextInputFormatter {
    DecimalTextInputFormatter({this.decimalRange})
      : assert(decimalRange == null || decimalRange > 0);
    
    final int decimalRange;
    
    @override
    TextEditingValue formatEditUpdate(
    TextEditingValue oldValue, // unused.
    TextEditingValue newValue,
    ) {
    TextSelection newSelection = newValue.selection;
    String truncated = newValue.text;
    
    if (decimalRange != null) {
      String value = newValue.text;
    
      if (value.contains(',') ||
          value.contains('-') ||
          value.contains(' ') ||
          value.contains('..')) {
        truncated = oldValue.text;
        newSelection = oldValue.selection;
      } else 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;
    

    } }

提交回复
热议问题