Flutter TextField仅输入十进制数字

问题描述 投票:0回答:2

我想在TextField中输入Flutter中的十进制数。我试过下面的代码,但那不起作用。它允许alpha(a-z)和特殊字符。

TextField(
  controller:
      new TextEditingController(text: listDisplay[position].getBlockQty(),
  ),       
  textAlign: TextAlign.center,
  maxLines: 1,       
  keyboardType: TextInputType.numberWithOptions(
      decimal: true,
      signed: false),       
),
flutter textfield
2个回答
2
投票

我在我的一个项目中使用了这个代码,并且工作正常。我希望它会对你有所帮助。

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

enter image description here


0
投票

你可以在这种情况下使用TextInputFormatter

这是一个相同的例子,

子类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;
    }
  }
}

将其与文本字段一起使用

final _amountValidator = RegExInputFormatter.withRegex('^\$|^(0|([1-9][0-9]{0,}))(\\.[0-9]{0,})?\$');
...
TextField(
  inputFormatters: [_amountValidator],
  keyboardType: TextInputType.numberWithOptions(
    decimal: true,
     signed: false,
   ),
 )
© www.soinside.com 2019 - 2024. All rights reserved.