flutter TextField 键盘弹出和隐藏,限制仅英文输入, 禁止联想输入

  var focusNode = FocusNode();
  RegExp englishRegExp = RegExp(r'(^[a-zA-Z]*$)');
  String inputText = '';
  
  showKeyboard() {
	focusNode.requestFocus();
  }
  dismissKeyboard() {
	focusNode.unfocus();
  }
  getTextField() {
    var currentModel = currentItem();
    return TextField(
      controller: controller,
      focusNode: focusNode,
      style: TextStyle(color: Colors.transparent),
      //字体透明
      showCursor: false,
      enableInteractiveSelection: false,
      keyboardType: TextInputType.visiblePassword,
      decoration: InputDecoration(
        ///边框不可见
        border: InputBorder.none,
      ),
      onChanged: (value) {
        ///禁止联想输入
        var length = value.length - inputText.length;
        if (length > 1) {
          controller.value = TextEditingValue(
              text: inputText,
              selection: TextSelection.collapsed(offset: inputText.length));
          return;
        }

        ///禁止非英文输入(不要用inputFormatters:[WhitelistingTextInputFormatter(xxx)],空格输入,最后一个字符删除等有问题);
        if (!englishRegExp.hasMatch(value)) {
          controller.value = TextEditingValue(
              text: inputText,
              selection: TextSelection.collapsed(offset: inputText.length));
          return;
        }
        setState(() {
          ///删除键差值是-1(没有删除键的回调,只能用-1来做校验,可能会有联想输入刚好差值为-1的情况)
          if (length == -1 || length == 1) {
            inputText = value;
          }
          controller.value = TextEditingValue(
              text: inputText,
              selection: TextSelection.collapsed(offset: inputText.length));
        });
        ///判断是否输入完成(达到输入上限)
        inputWordCompleted();
      },
    );
  }

你可能感兴趣的:(flutter,ios,flutter,android)