如何检测颤动输入字段中的空格

How to detect whitespaces in flutter input field

我一直在尝试检测我的 Flutter 应用程序输入字段中的空格。我制作了一个自定义输入字段,我在其中使用控制器并对其进行验证。我已成功完成所有验证,但我无法使用正则表达式检测到空格。如果用户在用户名中输入了空格,我不想 trim 我只想检测和验证用户错误消息的字符串。这是我的代码,虽然它不是必需的,但我还是把它放了

InputText(
                                  onTap: () {
                                    FocusScopeNode currentFocus =
                                        FocusScope.of(context);

                                    if (!currentFocus.hasPrimaryFocus &&
                                        currentFocus.focusedChild != null) {
                                      FocusManager.instance.primaryFocus
                                          ?.unfocus();
                                    }
                                  },
                                  controller: userName,
                                  buttonText: "*Username",
                                ),

验证:

  void vaildation() async {
    if (userName.text.isEmpty && email.text.isEmpty && password.text.isEmpty) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text("Please fill in fields to sign up"),
          duration: Duration(milliseconds: 600),
        ),
      );
    } else if (email.text.isEmpty) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text("Please enter an email"),
          duration: Duration(milliseconds: 600),
        ),
      );
    } else if (!regExp.hasMatch(email.text)) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text("Please enter valid email"),
          duration: Duration(milliseconds: 600),
        ),
      );
    } else if (password.text.isEmpty) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text("Please enter a password"),
          duration: Duration(milliseconds: 600),
        ),
      );
    } else if (phoneNumber.text.isEmpty) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text("Please enter your phone number"),
          duration: Duration(milliseconds: 600),
        ),
      );
    } else {
      submit();
    }
  }

验证检查:

AppButton(
                                  buttonText: "Sign up",
                                  onTap: () {
                                    vaildation();
                                  },
                                ),

在您的验证函数中,没有实际尝试验证用户名的地方。添加以下内容以检查用户名中的空格。

else if (RegExp(r"\s").hasMatch(username.text)) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text("Please enter valid username"),
          duration: Duration(milliseconds: 600),
        ),
      );
    }