Flutter:如何使用maxLength属性验证文本字段字符

时间:2019-08-20 16:16:13

标签: flutter

我想用分配给窗口小部件的maxLength属性验证文本字段字符。

我使用下面的代码分配maxLength

TextField field = new TextField(
      autofocus: true,
      maxLength: 4,
);

是否有任何方法可以获取此maxLength值,以使用maxLength属性验证输入的字符?

2 个答案:

答案 0 :(得分:0)

1。在TextField中需要一些GlobalKey

ListTile(
  title: Text(
    "Some Random Field",
    style: TextStyle(fontWeight: FontWeight.bold),
  ),
  subtitle: TextField(
    key: _keyTextField, // add some key here
    maxLength: 4,
  ),
),

2。通过探索currentWidget值获取maxLength值

  void handleButton() {
    int maxLength = getMaxLength();
    print("maxLength : $maxLength");
  }

  int getMaxLength() {
    String properties = _keyTextField.currentWidget.toString();
    RegExp exp = new RegExp(r'(maxLength: )\d+');
    RegExpMatch matches = exp.firstMatch(properties);
    if (matches != null && matches.groupCount > 0) {
      String maxLengthStrings = matches.group(0);
      return int.parse(maxLengthStrings.split("maxLength: ").last);
    } else {
      print("Not found");
      return 0;
    }
  }

演示

Demo

完整代码存储区

您可以在此处查看TextFieldScreen小部件。 Github

答案 1 :(得分:0)

我找到了一种简单的方法

   TextEditingController controller = new TextEditingController();
   controller.addListener(() {
      if(controller.text.length == field.maxLength) { // TextField field = new TextField
        print("User trying to add more characters");
      }
    });