Flutter TextField input only decimal numbers

后端 未结 3 1537
醉酒成梦
醉酒成梦 2021-01-05 16:56

I want to input only decimal number in TextField in Flutter. I tried below code but that\'s not working. It allows alpha (a-z) and special characte

3条回答
  •  别那么骄傲
    2021-01-05 17:30

    You can use TextInputFormatter for this case.

    Here is an example for the same,

    Subclass TextInputFormatter

    import 'package:flutter/services.dart';
    
    class RegExInputFormatter implements TextInputFormatter {
      final RegExp _regExp;
    
      RegExInputFormatter._(this._regExp);
    
      factory RegExInputFormatter.withRegex(String regexString) {
        try {
          final regex = RegExp(regexString);
          return RegExInputFormatter._(regex);
        } catch (e) {
          // Something not right with regex string.
          assert(false, e.toString());
          return null;
        }
      }
    
      @override
      TextEditingValue formatEditUpdate(
          TextEditingValue oldValue, TextEditingValue newValue) {
        final oldValueValid = _isValid(oldValue.text);
        final newValueValid = _isValid(newValue.text);
        if (oldValueValid && !newValueValid) {
          return oldValue;
        }
        return newValue;
      }
    
      bool _isValid(String value) {
        try {
          final matches = _regExp.allMatches(value);
          for (Match match in matches) {
            if (match.start == 0 && match.end == value.length) {
              return true;
            }
          }
          return false;
        } catch (e) {
          // Invalid regex
          assert(false, e.toString());
          return true;
        }
      }
    }
    
    

    Use it in with your textfield

    final _amountValidator = RegExInputFormatter.withRegex('^\$|^(0|([1-9][0-9]{0,}))(\\.[0-9]{0,})?\$');
    ...
    TextField(
      inputFormatters: [_amountValidator],
      keyboardType: TextInputType.numberWithOptions(
        decimal: true,
         signed: false,
       ),
     )
    

提交回复
热议问题