Flutter TextField input only decimal numbers

萝らか妹 提交于 2020-06-11 06:01:11

问题


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 characters.

TextField(
  controller:
      new TextEditingController(text: listDisplay[position].getBlockQty(),
  ),       
  textAlign: TextAlign.center,
  maxLines: 1,       
  keyboardType: TextInputType.numberWithOptions(
      decimal: true,
      signed: false),       
),

回答1:


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,
   ),
 )



回答2:


I have used this code in one of my Project and its working fine. I hope it will helps you.

TextField(
         decoration: InputDecoration(
         border: InputBorder.none,
         hintText: "Amount",
         hintStyle:
         TextStyle(color: Colors.grey, fontSize: 12.0),
         ),
         style: TextStyle(color: Colors.black, fontSize: 12.0),
         controller: _amountController[index],
         textInputAction: TextInputAction.done,
         keyboardType: TextInputType.numberWithOptions(decimal: true),)



来源:https://stackoverflow.com/questions/55631224/flutter-textfield-input-only-decimal-numbers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!