Allow only two decimal number in flutter input?

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

    Maybe a little late for you, but I also improved a little:

    1. Allow only 1 .
    2. Allow negative
    3. Place negative sign on beginning

    Hope it helps ;)

    import 'package:flutter/services.dart';
    
    class NumberTextInputFormatter extends TextInputFormatter {
      NumberTextInputFormatter({this.decimalRange}) : assert(decimalRange == null || decimalRange > 0);
    
      final int decimalRange;
    
      @override
      TextEditingValue formatEditUpdate(TextEditingValue oldValue, TextEditingValue newValue) {
        TextEditingValue _newValue = this.sanitize(newValue);
        String text = _newValue.text;
    
        if (decimalRange == null) {
          return _newValue;
        }
    
        if (text == '.') {
          return TextEditingValue(
            text: '0.',
            selection: _newValue.selection.copyWith(baseOffset: 2, extentOffset: 2),
            composing: TextRange.empty,
          );
        }
    
        return this.isValid(text) ? _newValue : oldValue;
      }
    
      bool isValid(String text) {
        int dots = '.'.allMatches(text).length;
    
        if (dots == 0) {
          return true;
        }
    
        if (dots > 1) {
          return false;
        }
    
        return text.substring(text.indexOf('.') + 1).length <= decimalRange;
      }
    
      TextEditingValue sanitize(TextEditingValue value) {
        if (false == value.text.contains('-')) {
          return value;
        }
    
        String text = '-' + value.text.replaceAll('-', '');
    
        return TextEditingValue(text: text, selection: value.selection, composing: TextRange.empty);
      }
    }
    

    and (don't forget to import the previous class)

    import 'package:flutter/material.dart';
    import 'package:flutter/services.dart';
    
    class NumberFormField extends StatelessWidget {
      final InputDecoration decoration;
      final TextEditingController controller;
      final int decimalRange;
    
      const NumberFormField({Key key, this.decoration, this.controller, this.decimalRange}) :super(key: key);
    
      @override
      Widget build(BuildContext context) {
        return TextFormField(
          decoration: this.decoration,
          controller: this.controller,
          keyboardType: TextInputType.numberWithOptions(decimal: true),
          inputFormatters: [
            WhitelistingTextInputFormatter(RegExp(r'[\d+\-\.]')),
            NumberTextInputFormatter(decimalRange: this.decimalRange),
          ],
        );
      }
    }
    

提交回复
热议问题