如何在Flutter中验证用户名TextFormField输入不正确

huangapple go评论53阅读模式
英文:

How to validate username TextFormField when incorrect in Flutter

问题

我正在尝试在登录按钮按下时验证我的表单。当所有字段都为空时,在客户端上可以正常工作,但是使用了我的开关/案例后似乎不起作用。我认为这可能与我的验证函数有关,但我无法确定。我认为布尔值在 MySOAPRequest 中设置正确,因为当我按下登录按钮然后更新公司或 PIN 字段时,错误消息显示在用户名字段上,但应该在登录按钮按下时显示。

登录页面带有文本字段和登录按钮

CustomTextField(
  key: _customTextFieldKey,
  companyController: _companyController,
  usernameController: _usernameController,
  pinController: _pinController,
),
const SizedBox(height: 20),
OutlinedButton(
  onPressed: () {
    FocusManager.instance.primaryFocus?.unfocus();
    String lcomp = Globals().lcomp = _companyController.text.trim();
    String luser = Globals().luser = _usernameController.text.trim();
    String lpin = Globals().lpin = _pinController.text.trim();

    if (lcomp.isNotEmpty &&
        luser.isNotEmpty &&
        lpin.isNotEmpty &&
        !_customTextFieldKey.currentState!.hasError()) {
      MySOAPRequest(
        lcomp: lcomp,
        luser: luser,
        lpin: lpin,
        onLoginSuccess: _saveCredentials,
      ).makeSOAPRequest(context);
    } else {
      _customTextFieldKey.currentState?.validate();
    }
  },
  child: const Text('登录'),
),

MySOAPRequest 页面代码

final String lcomp;
final String luser;
final String lpin;
final Function(bool) onLoginSuccess; // 定义 onLoginSuccess 参数

MySOAPRequest({
  required this.lcomp,
  required this.luser,
  required this.lpin,
  required this.onLoginSuccess,
});

switch (logonState) {
  case '1':
    // 如果登录状态为 1,则导航到 Landing 页面
    loginFlushbar(context);
    navigateToSubPages(context);
    onLoginSuccess(true);
    break;
  case '3':
    flushbar(context, '不正确的用户名', '请再试一次或联系您的管理员,如果问题仍然存在。');
    onLoginSuccess(false);
    break;
  default:
    flushbar(context, '未知错误', '发生未知错误。请再试一次或联系您的管理员。');
    Globals().usernameHasError = true;
    Globals().errorText = '不正确的用户名';
    Globals().customTextFieldKey.currentState?.validate();
    onLoginSuccess(false);
    break;
}

用户名字段文本

class CustomTextFieldState extends State<CustomTextField> {
  final _formKey = GlobalKey<FormState>();
  //final _usernameKey = Globals().customTextFieldKey;

  String _company = '';
  String _username = '';
  String _pin = '';

  bool _companyHasError = false;
  bool _usernameHasError = false;
  bool _pinHasError = false;

  bool hasError() {
    return _usernameHasError || _companyHasError || _pinHasError;
  }

  void validate() {
    setState(() {
      if (_formKey.currentState != null) {
        _companyHasError =
            !_formKey.currentState!.validate() || _company.isEmpty;
        _usernameHasError =
            !_formKey.currentState!.validate() || _username.isEmpty;
        _pinHasError = !_formKey.currentState!.validate() || _pin.isEmpty;
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    String lcomp = widget.companyController.text.trim();

    return Form(
      key: _formKey,
      autovalidateMode: AutovalidateMode.disabled,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisAlignment: MainAxisAlignment.start,
        children: [
          Padding(
            padding: const EdgeInsets.only(bottom: 20.0),
            // 公司文本字段
            child: TextFormField(
              controller: widget.companyController,
              decoration: InputDecoration(
                // ...
              ),
              autovalidateMode: AutovalidateMode.onUserInteraction,
              validator: (value) {
                if (value == null || value.isEmpty) {
                  return '请输入您的公司名称!';
                }
                return null;
              },
              onChanged: (value) {
                setState(() {
                  _company = value;
                  _companyHasError = false;
                });
              },
              onFieldSubmitted: (value) {
                setState(() {
                  _companyHasError = !_formKey.currentState!.validate();
                });
              },
            ),
          ),
          // 用户名文本字段
          TextFormField(
            controller: widget.usernameController,
            //key: _usernameKey,
            decoration: InputDecoration(
              // ...
            ),
            autovalidateMode: AutovalidateMode.onUserInteraction,
            validator: (value) {
              if (value == null || value.isEmpty) {
                return '请输入您的用户名!';
              }
              return null;
            },
            onChanged: (value) {
              setState(() {
                _username = value;
                _usernameHasError = false;
                Globals().usernameHasError = false;
              });
            },
            onFieldSubmitted: (value) {
              setState(() {
                _usernameHasError = !_formKey.currentState!.validate();
              });
            },
          ),
          // ...
        ],
      ),
    );
  }
}

以上是您提供的代码的翻译。如果您有其他问题或需要进一步的帮助,请告诉我。

英文:

I am trying to validate my form on login button press. It works perfectly fine on client side when all fields are empty however with my switch/case it does not appear to work. I believe it may be related to my validation function but I cannot pinpoint it. I believe the booleans are being set correctly in MySOAPRequest since when I press the login button then update the company or pin field the error message shows on the username field but it should show on login button press.

Login page with text fields and login button

                          CustomTextField(
key: _customTextFieldKey,
companyController: _companyController,
usernameController: _usernameController,
pinController: _pinController,
),
const SizedBox(height: 20),
OutlinedButton(
onPressed: () {
FocusManager.instance.primaryFocus?.unfocus();
String lcomp = Globals().lcomp =
_companyController.text.trim();
String luser = Globals().luser =
_usernameController.text.trim();
String lpin =
Globals().lpin = _pinController.text.trim();
if (lcomp.isNotEmpty &amp;&amp;
luser.isNotEmpty &amp;&amp;
lpin.isNotEmpty &amp;&amp;
!_customTextFieldKey.currentState!
.hasError()) {
MySOAPRequest(
lcomp: lcomp,
luser: luser,
lpin: lpin,
onLoginSuccess: _saveCredentials,
).makeSOAPRequest(context);
} else {
_customTextFieldKey.currentState?.validate();
}
},
child: const Text(&#39;Login&#39;),
),

MySOAPRequest page code

  final String lcomp;
final String luser;
final String lpin;
final Function(bool) onLoginSuccess; // define the onLoginSuccess parameter
MySOAPRequest({
required this.lcomp,
required this.luser,
required this.lpin,
required this.onLoginSuccess,
});
switch (logonState) {
case &#39;1&#39;:
// Navigate to the Landing page if the logon state is 1
// ignore: use_build_context_synchronously
loginFlushbar(context);
// ignore: use_build_context_synchronously
navigateToSubPages(context);
onLoginSuccess(true);
break;
case &#39;3&#39;:
// ignore: use_build_context_synchronously
flushbar(context, &#39;Incorrect User Name&#39;,
&#39;Please try again or contact your administrator if this issue persists.&#39;);
onLoginSuccess(false);
break;
default:
// ignore: use_build_context_synchronously
flushbar(context, &#39;Unknown Error&#39;,
&#39;An unknown error occurred. Please try again or contact your administrator.&#39;);
Globals().usernameHasError = true;
Globals().errorText = &#39;Incorrect User Name&#39;;
Globals().customTextFieldKey.currentState?.validate();
onLoginSuccess(false);
break;
}

Username field text

class CustomTextFieldState extends State&lt;CustomTextField&gt; {
final _formKey = GlobalKey&lt;FormState&gt;();
//final _usernameKey = Globals().customTextFieldKey;
String _company = &#39;&#39;;
String _username = &#39;&#39;;
String _pin = &#39;&#39;;
bool _companyHasError = false;
bool _usernameHasError = false;
bool _pinHasError = false;
bool hasError() {
return _usernameHasError || _companyHasError || _pinHasError;
}
void validate() {
setState(() {
if (_formKey.currentState != null) {
_companyHasError =
!_formKey.currentState!.validate() || _company.isEmpty;
_usernameHasError =
!_formKey.currentState!.validate() || _username.isEmpty;
_pinHasError = !_formKey.currentState!.validate() || _pin.isEmpty;
}
});
}
@override
Widget build(BuildContext context) {
String lcomp = widget.companyController.text.trim();
return Form(
key: _formKey,
autovalidateMode: AutovalidateMode.disabled,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.start,
children: [
Padding(
padding: const EdgeInsets.only(bottom: 20.0),
//!--- COMPANY TEXT FIELD --- //
child: TextFormField(
controller: widget.companyController,
decoration: InputDecoration(
contentPadding: const EdgeInsets.only(left: 20),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(30),
borderSide: const BorderSide(
color: Color(0xff185C91),
),
),
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(30),
borderSide: const BorderSide(
color: ThemeClass.primaryColor,
),
),
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(30),
borderSide: const BorderSide(
color: Color(0xff185C91),
),
),
errorBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(30),
borderSide: const BorderSide(color: Colors.red),
),
disabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(30),
borderSide: const BorderSide(color: Color(0x00232323)),
),
suffixIcon: const Icon(Icons.corporate_fare_outlined,
color: ThemeClass.primaryColor),
labelText: &quot;Company Name&quot;,
labelStyle: const TextStyle(
fontSize: 14.0,
decoration: TextDecoration.none,
),
hintText: &#39;Enter Company Name&#39;,
hintStyle: const TextStyle(
fontSize: 14.0,
),
errorText: _companyHasError
? &#39;Please enter a valid company name!&#39;
: ((_company.isNotEmpty &amp;&amp;
!Globals().resultList.contains(lcomp))
? &#39;Please enter a valid company name!&#39;
: null),
),
autovalidateMode: AutovalidateMode.onUserInteraction,
validator: (value) {
if (value == null || value.isEmpty) {
return &#39;Please enter your company name!&#39;;
}
return null;
},
onChanged: (value) {
setState(() {
_company = value;
_companyHasError = false;
});
},
onFieldSubmitted: (value) {
setState(() {
_companyHasError = !_formKey.currentState!.validate();
});
},
),
),
//!--- END COMPANY TEXT FIELD --- //
//!--- USERNAME TEXT FIELD --- //
TextFormField(
controller: widget.usernameController,
//key: _usernameKey,
decoration: InputDecoration(
contentPadding: const EdgeInsets.only(left: 20),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(30),
borderSide: const BorderSide(
color: Color(0xff185C91),
),
),
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(30),
borderSide: const BorderSide(
color: ThemeClass.primaryColor,
),
),
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(30),
borderSide: const BorderSide(
color: Color(0xff185C91),
),
),
errorBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(30),
borderSide: const BorderSide(color: Colors.red),
),
disabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(30),
borderSide: const BorderSide(color: Color(0x00232323)),
),
suffixIcon: const Icon(Icons.person_outlined,
color: ThemeClass.primaryColor),
labelText: &quot;Username&quot;,
labelStyle: const TextStyle(
fontSize: 14.0,
decoration: TextDecoration.none,
),
hintText: &#39;Enter username&#39;,
hintStyle: const TextStyle(
fontSize: 14.0,
),
errorText: _usernameHasError
? &#39;Please enter a valid username!&#39;
: Globals().usernameHasError
? Globals().errorText
: null,
),
autovalidateMode: AutovalidateMode.onUserInteraction,
validator: (value) {
if (value == null || value.isEmpty) {
return &#39;Please enter your username!&#39;;
}
return null;
},
onChanged: (value) {
setState(() {
_username = value;
_usernameHasError = false;
Globals().usernameHasError = false;
});
},
onFieldSubmitted: (value) {
setState(() {
_usernameHasError = !_formKey.currentState!.validate();
});
},
),
//!--- END USERNAME TEXT FIELD --- //
const SizedBox(height: 20),
//!--- PIN TEXT FIELD --- //
TextFormField(
controller: widget.pinController,
inputFormatters: [
LengthLimitingTextInputFormatter(6),
FilteringTextInputFormatter.digitsOnly
],
obscureText: true,
keyboardType: TextInputType.number,
decoration: InputDecoration(
contentPadding: const EdgeInsets.only(left: 20),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(30),
borderSide: const BorderSide(
color: Color(0xff185C91),
),
),
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(30),
borderSide: const BorderSide(
color: ThemeClass.primaryColor,
),
),
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(30),
borderSide: const BorderSide(
color: Color(0xff185C91),
),
),
errorBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(30),
borderSide: const BorderSide(color: Colors.red),
),
disabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(30),
borderSide: const BorderSide(color: Color(0x00232323)),
),
suffixIcon: const Icon(Icons.pin_outlined,
color: ThemeClass.primaryColor),
labelText: &quot;PIN&quot;,
labelStyle: const TextStyle(
fontSize: 14.0,
decoration: TextDecoration.none,
),
hintText: &#39;Enter PIN&#39;,
hintStyle: const TextStyle(
fontSize: 14.0,
),
errorText: _pinHasError
? &#39;Please enter a valid PIN!&#39;
: _pin.length &lt; 4 &amp;&amp; _pin.isNotEmpty
? &#39;PIN is too short!&#39;
: null,
),
autovalidateMode: AutovalidateMode.onUserInteraction,
validator: (value) {
if (value == null || value.isEmpty) {
return &#39;Please enter your PIN!&#39;;
}
return null;
},
onChanged: (value) {
setState(() {
_pin = value;
_pinHasError = false;
});
},
onFieldSubmitted: (value) {
setState(() {
_pinHasError = !_formKey.currentState!.validate();
});
},
),
//!--- END PIN TEXT FIELD --- //
],
),
);
}
}
</details>
# 答案1
**得分**: 1
I just saw something bad you are doing on the switch case,
ignore: use_build_context_synchronously
there is a reason why you should not call the build context asynchronously, it may have been unmounted since you passed it around
if you are using a stateful widget, which appears to be so, you can define your context-dependent functions outside the build widget like this
StatefulWidget {
void _loginFlushBar() => loginFlushbar(context);
void _navigateToSubPages => navigateToSubPages(context);
Widget build(BuildContext context) {
// Your widgets
}
}
<details>
<summary>英文:</summary>
i just saw something bad you are doing on the switch case,
ignore: use_build_context_synchronously
there is a reason why you should not call the build context asynchronously, it may have been unmounted since you passed it aroud
if you are using a stateful widget, which appears to be so, you can define your context dependendant functions outside the build widget like this
StatefulWidget{
void _loginFlushBar() =&gt; loginFlushbar(context);
void _navigateToSubPages =&gt; navigateToSubPages(context);
Widget build(Buildcontext context){
//Your widgets
}
}
</details>
# 答案2
**得分**: 1
将您的 `TextFormField` 包裹在一个 `Form` 小部件中,并为 `Form` 提供一个 `GlobalKey&lt;FormState&gt;` 作为其键。然后您可以使用 `_formKey.currentState!.validate()` 进行验证。
<details>
<summary>英文:</summary>
Wrap your `TextFormField` in a `Form` widget and provide a `GlobalKey&lt;FormState&gt;` to the `Form` as its key. Then you can validate it with `_formKey.currentState!.validate()`.
</details>

huangapple
  • 本文由 发表于 2023年6月29日 22:31:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/76582047.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定