0

在此处输入图像描述

这是我的 UI 代码

Container(
           padding: EdgeInsets.fromLTRB(10, 10, 10, 0),
           child:TextFormField(
             controller: name,
           textInputAction: TextInputAction.next,
           decoration: InputDecoration(
             prefixIcon: Icon(
               Icons.person,
             ),
            hintText: "First name",
             border: OutlineInputBorder(
            borderSide: BorderSide(color: Colors.purpleAccent),
            borderRadius: BorderRadius.circular(10),
          ),
        ),
      ),
    ),
            Container(
           padding: EdgeInsets.fromLTRB(10, 10, 10, 0),
           child:TextFormField( 
             controller: second_name,
           textInputAction: TextInputAction.next,
           decoration: InputDecoration(
             prefixIcon: Icon(
               Icons.person,
             ),
            hintText: "Second Name",
             border: OutlineInputBorder(
            borderSide: BorderSide(color: Colors.purpleAccent),
            borderRadius: BorderRadius.circular(10),
          ),
        ),
      ),
    ), 
            Container(
           padding: EdgeInsets.fromLTRB(10, 10, 10, 0),
           child:TextFormField(
           textInputAction: TextInputAction.next,
           decoration: InputDecoration(
             prefixIcon: Icon(
               Icons.mail,
             ),
            hintText: "Email-id ",
             border: OutlineInputBorder(
            borderSide: BorderSide(color: Colors.purpleAccent),
            borderRadius: BorderRadius.circular(10),
          ),
        ),
      ),
    ), Container(
           padding: EdgeInsets.fromLTRB(10, 10, 10, 0),
           child:TextFormField(
           textInputAction: TextInputAction.next,
           decoration: InputDecoration(
             prefixIcon: Icon(
               Icons.vpn_key,
             ),
            hintText: "Password",
             border: OutlineInputBorder(
            borderSide: BorderSide(color: Colors.purpleAccent),
            borderRadius: BorderRadius.circular(10),
          ),
        ),
      ),
    ), Container(
           padding: EdgeInsets.fromLTRB(10, 10, 10, 0),
           child:TextFormField(
           textInputAction: TextInputAction.next,
           decoration: InputDecoration(
             prefixIcon: Icon(
               Icons.vpn_key,
             ),
            hintText: "Confirm Password",
             border: OutlineInputBorder(
            borderSide: BorderSide(color: Colors.purpleAccent),
            borderRadius: BorderRadius.circular(10),
          ),
        ),
      ),
    ),

现在有一个注册按钮,现在我想在用户输入一些数据后在每个容器的底部显示一个文本,如果数据不符合某些给定条件,如“密码不匹配”,那么如何在我的按钮的 onpressed 功能中显示该功能或要执行的操作。请为此提供一些代码。提前致谢。

这是一个示例图片,所以红色的文字说“这个 eamil 不存在......”如何显示这样的文字..

4

3 回答 3

0

在 TextFormField 中,有一个验证器函数。您可以使用它来显示错误消息。

  Container(
       padding: EdgeInsets.fromLTRB(10, 10, 10, 0),
       child:TextFormField(
         controller: name,
       validator: (value){
       if(value== null || value.isEmpty){
       return 'Name must not be empty';
       }
       return null;
       }
       textInputAction: TextInputAction.next,
       decoration: InputDecoration(
         prefixIcon: Icon(
           Icons.person,
         ),
        hintText: "First name",
         border: OutlineInputBorder(
        borderSide: BorderSide(color: Colors.purpleAccent),
        borderRadius: BorderRadius.circular(10),
      ),
    ),
  ),
),

您还可以将整个屏幕包装在 Form 小部件中,并使用 key: 属性来验证用户何时单击按钮。您仍然必须在 TextFormField 中传递验证器函数。表单小部件只是验证器功能特性的扩展。

 final _formKey = GlobalKey<FormState>();

 Form(
 key: _formKey,
 )

然后在您的按钮中添加 onChanged 此代码,以便在没有验证的情况下不会提交表单。

 onChanged: () {
              if (!_formKey.currentState!.validate()) {
              return;
             }
            // write code to save inputs here
            }

或者,您还可以使用验证器功能在 TextFormField 中添加 autovalidateMode: AutovalidateMode.always,以在用户交互时验证表单。此属性在表单小部件中也可用。

于 2021-11-25T17:42:09.400 回答
0

您可以使用 onChanged 属性。

onChanged: (text) {
   
  }
于 2021-11-25T16:12:35.473 回答
0

Please refer to below code

You can try either of the solutions

Solution 1: Autovalidation is disabled and only on user interaction, i.e on click of validate button text form field starts validation accordingly.

enter image description here enter image description here

class MainScreen extends StatelessWidget {
  MainScreen({Key key}) : super(key: key);

  final TextEditingController addressController = TextEditingController();
  final FocusNode addressFocus = FocusNode();
  final TextEditingController stateController = TextEditingController();
  final FocusNode stateFocus = FocusNode();
  final _validationKey = GlobalKey<FormState>();

  int validateAddress(String address) {
    String patttern = r'(^[a-zA-Z0-9 ,.-]*$)';
    RegExp regExp = new RegExp(patttern);
    if (address.isEmpty || address.length == 0) {
      return 1;
    } else if (address.length < 10) {
      return 3;
    } else {
      return 0;
    }
  }

  int validateState(String state) {
    String patttern = r'(^[a-zA-Z0-9 ,.-]*$)';
    RegExp regExp = new RegExp(patttern);
    if (state.isEmpty || state.length == 0) {
      return 1;
    } else {
      return 0;
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.lightBlue,
        automaticallyImplyLeading: true,
        leading: Icon(
          Icons.arrow_back,
        ),
        title: Text("Example"),
        centerTitle: true,
      ),
      body: Container(
        padding: EdgeInsets.all(15.0),
        child: Column(
          children: [
            Form(
              key: _validationKey,
              child: Column(
                children: [
                  /* State */
                  TextFormField(
                    autovalidateMode: AutovalidateMode.onUserInteraction,
                    /* autovalidate is disabled */
                    controller: stateController,
                    inputFormatters: [
                      FilteringTextInputFormatter.deny(RegExp(r"\s\s")),
                      FilteringTextInputFormatter.deny(RegExp(
                          r'(\u00a9|\u00ae|[\u2000-\u3300]|\ud83c[\ud000-\udfff]|\ud83d[\ud000-\udfff]|\ud83e[\ud000-\udfff])')),
                    ],
                    keyboardType: TextInputType.text,
                    maxLength: 160,
                    onChanged: (val) {},
                    maxLines: 1,
                    validator: (value) {
                      int res = validateAddress(value);
                      if (res == 1) {
                        return "Please enter state";
                      } else {
                        return null;
                      }
                    },
                    focusNode: stateFocus,
                    autofocus: false,
                    decoration: InputDecoration(
                      errorMaxLines: 3,
                      counterText: "",
                      filled: true,
                      fillColor: Colors.white,
                      focusedBorder: OutlineInputBorder(
                        borderRadius: BorderRadius.all(Radius.circular(4)),
                        borderSide: BorderSide(
                          width: 1,
                          color: Color(0xffE5E5E5),
                        ),
                      ),
                      disabledBorder: OutlineInputBorder(
                        borderRadius: BorderRadius.all(Radius.circular(4)),
                        borderSide: BorderSide(
                          width: 1,
                          color: Color(0xffE5E5E5),
                        ),
                      ),
                      enabledBorder: OutlineInputBorder(
                        borderRadius: BorderRadius.all(Radius.circular(4)),
                        borderSide: BorderSide(
                          width: 1,
                          color: Color(0xffE5E5E5),
                        ),
                      ),
                      border: OutlineInputBorder(
                        borderRadius: BorderRadius.all(Radius.circular(4)),
                        borderSide: BorderSide(
                          width: 1,
                        ),
                      ),
                      errorBorder: OutlineInputBorder(
                          borderRadius: BorderRadius.all(Radius.circular(4)),
                          borderSide: BorderSide(
                            width: 1,
                            color: Colors.red,
                          )),
                      focusedErrorBorder: OutlineInputBorder(
                        borderRadius: BorderRadius.all(Radius.circular(4)),
                        borderSide: BorderSide(
                          width: 1,
                          color: Colors.red,
                        ),
                      ),
                      hintText: "Enter state" ?? "",
                    ),
                  ),
                  SizedBox(
                    height: 15.0,
                  ),

                  /* Address */
                  TextFormField(
                    autovalidateMode: AutovalidateMode.onUserInteraction,
                    /* autovalidate is disabled */
                    controller: addressController,
                    inputFormatters: [
                      FilteringTextInputFormatter.deny(RegExp(r"\s\s")),
                      FilteringTextInputFormatter.deny(RegExp(
                          r'(\u00a9|\u00ae|[\u2000-\u3300]|\ud83c[\ud000-\udfff]|\ud83d[\ud000-\udfff]|\ud83e[\ud000-\udfff])')),
                    ],
                    keyboardType: TextInputType.text,
                    maxLength: 60,
                    onChanged: (val) {},
                    maxLines: 1,
                    validator: (value) {
                      int res = validateAddress(value);
                      if (res == 1) {
                        return "Please enter address";
                      } else if (res == 3) {
                        return "Please enter minimum 10 characters";
                      } else {
                        return null;
                      }
                    },
                    focusNode: addressFocus,
                    autofocus: false,
                    decoration: InputDecoration(
                      errorMaxLines: 3,
                      counterText: "",
                      filled: true,
                      fillColor: Colors.white,
                      focusedBorder: OutlineInputBorder(
                        borderRadius: BorderRadius.all(Radius.circular(4)),
                        borderSide: BorderSide(
                          width: 1,
                          color: Color(0xffE5E5E5),
                        ),
                      ),
                      disabledBorder: OutlineInputBorder(
                        borderRadius: BorderRadius.all(Radius.circular(4)),
                        borderSide: BorderSide(
                          width: 1,
                          color: Color(0xffE5E5E5),
                        ),
                      ),
                      enabledBorder: OutlineInputBorder(
                        borderRadius: BorderRadius.all(Radius.circular(4)),
                        borderSide: BorderSide(
                          width: 1,
                          color: Color(0xffE5E5E5),
                        ),
                      ),
                      border: OutlineInputBorder(
                        borderRadius: BorderRadius.all(Radius.circular(4)),
                        borderSide: BorderSide(
                          width: 1,
                        ),
                      ),
                      errorBorder: OutlineInputBorder(
                          borderRadius: BorderRadius.all(Radius.circular(4)),
                          borderSide: BorderSide(
                            width: 1,
                            color: Colors.red,
                          )),
                      focusedErrorBorder: OutlineInputBorder(
                        borderRadius: BorderRadius.all(Radius.circular(4)),
                        borderSide: BorderSide(
                          width: 1,
                          color: Colors.red,
                        ),
                      ),
                      hintText: "Enter address" ?? "",
                    ),
                  ),
                ],
              ),
            ),
            SizedBox(
              height: 15.0,
            ),
            OutlinedButton(
              onPressed: () {
                _validationKey.currentState.validate();
                if (stateController.text.isEmpty) {
                  stateFocus.requestFocus();
                } else if (addressController.text.isEmpty ||
                    addressController.text.length < 10) {
                  addressFocus.requestFocus();
                }
              },
              child: Text("Validate"),
            )
          ],
        ),
      ),
    );
  }
}

Solution 2: Autovalidation is enabled always

enter image description here

class HomeScreen extends StatelessWidget {
  HomeScreen({Key key}) : super(key: key);

  final TextEditingController addressController = TextEditingController();
  final FocusNode addressFocus = FocusNode();
  final TextEditingController stateController = TextEditingController();
  final FocusNode stateFocus = FocusNode();
  final _validationKey = GlobalKey<FormState>();

  int validateAddress(String address) {
    String patttern = r'(^[a-zA-Z0-9 ,.-]*$)';
    RegExp regExp = new RegExp(patttern);
    if (address.isEmpty || address.length == 0) {
      return 1;
    } else if (address.length < 10) {
      return 3;
    } else {
      return 0;
    }
  }

  int validateState(String state) {
    String patttern = r'(^[a-zA-Z0-9 ,.-]*$)';
    RegExp regExp = new RegExp(patttern);
    if (state.isEmpty || state.length == 0) {
      return 1;
    } else {
      return 0;
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.lightBlue,
        automaticallyImplyLeading: true,
        leading: Icon(
          Icons.arrow_back,
        ),
        title: Text("Example"),
        centerTitle: true,
      ),
      body: Container(
        padding: EdgeInsets.all(15.0),
        child: Column(
          children: [
            Form(
              key: _validationKey,
              child: Column(
                children: [
                  /* State */
                  TextFormField(
                    autovalidateMode: AutovalidateMode.always,
                    /* autovalidate is set to true */
                    controller: stateController,
                    inputFormatters: [
                      FilteringTextInputFormatter.deny(RegExp(r"\s\s")),
                      FilteringTextInputFormatter.deny(RegExp(
                          r'(\u00a9|\u00ae|[\u2000-\u3300]|\ud83c[\ud000-\udfff]|\ud83d[\ud000-\udfff]|\ud83e[\ud000-\udfff])')),
                    ],
                    keyboardType: TextInputType.text,
                    maxLength: 160,
                    onChanged: (val) {},
                    maxLines: 1,
                    validator: (value) {
                      int res = validateAddress(value);
                      if (res == 1) {
                        return "Please enter state";
                      } else {
                        return null;
                      }
                    },
                    focusNode: stateFocus,
                    autofocus: false,
                    decoration: InputDecoration(
                      errorMaxLines: 3,
                      counterText: "",
                      filled: true,
                      fillColor: Colors.white,
                      focusedBorder: OutlineInputBorder(
                        borderRadius: BorderRadius.all(Radius.circular(4)),
                        borderSide: BorderSide(
                          width: 1,
                          color: Color(0xffE5E5E5),
                        ),
                      ),
                      disabledBorder: OutlineInputBorder(
                        borderRadius: BorderRadius.all(Radius.circular(4)),
                        borderSide: BorderSide(
                          width: 1,
                          color: Color(0xffE5E5E5),
                        ),
                      ),
                      enabledBorder: OutlineInputBorder(
                        borderRadius: BorderRadius.all(Radius.circular(4)),
                        borderSide: BorderSide(
                          width: 1,
                          color: Color(0xffE5E5E5),
                        ),
                      ),
                      border: OutlineInputBorder(
                        borderRadius: BorderRadius.all(Radius.circular(4)),
                        borderSide: BorderSide(
                          width: 1,
                        ),
                      ),
                      errorBorder: OutlineInputBorder(
                          borderRadius: BorderRadius.all(Radius.circular(4)),
                          borderSide: BorderSide(
                            width: 1,
                            color: Colors.red,
                          )),
                      focusedErrorBorder: OutlineInputBorder(
                        borderRadius: BorderRadius.all(Radius.circular(4)),
                        borderSide: BorderSide(
                          width: 1,
                          color: Colors.red,
                        ),
                      ),
                      hintText: "Enter state" ?? "",
                    ),
                  ),
                  SizedBox(
                    height: 15.0,
                  ),

                  /* Address */
                  TextFormField(
                    autovalidateMode: AutovalidateMode.always,
                    /* autovalidate is enabled */
                    controller: addressController,
                    inputFormatters: [
                      FilteringTextInputFormatter.deny(RegExp(r"\s\s")),
                      FilteringTextInputFormatter.deny(RegExp(
                          r'(\u00a9|\u00ae|[\u2000-\u3300]|\ud83c[\ud000-\udfff]|\ud83d[\ud000-\udfff]|\ud83e[\ud000-\udfff])')),
                    ],
                    keyboardType: TextInputType.text,
                    maxLength: 60,
                    onChanged: (val) {},
                    maxLines: 1,
                    validator: (value) {
                      int res = validateAddress(value);
                      if (res == 1) {
                        return "Please enter address";
                      } else if (res == 3) {
                        return "Please enter minimum 10 characters";
                      } else {
                        return null;
                      }
                    },
                    focusNode: addressFocus,
                    autofocus: false,
                    decoration: InputDecoration(
                      errorMaxLines: 3,
                      counterText: "",
                      filled: true,
                      fillColor: Colors.white,
                      focusedBorder: OutlineInputBorder(
                        borderRadius: BorderRadius.all(Radius.circular(4)),
                        borderSide: BorderSide(
                          width: 1,
                          color: Color(0xffE5E5E5),
                        ),
                      ),
                      disabledBorder: OutlineInputBorder(
                        borderRadius: BorderRadius.all(Radius.circular(4)),
                        borderSide: BorderSide(
                          width: 1,
                          color: Color(0xffE5E5E5),
                        ),
                      ),
                      enabledBorder: OutlineInputBorder(
                        borderRadius: BorderRadius.all(Radius.circular(4)),
                        borderSide: BorderSide(
                          width: 1,
                          color: Color(0xffE5E5E5),
                        ),
                      ),
                      border: OutlineInputBorder(
                        borderRadius: BorderRadius.all(Radius.circular(4)),
                        borderSide: BorderSide(
                          width: 1,
                        ),
                      ),
                      errorBorder: OutlineInputBorder(
                          borderRadius: BorderRadius.all(Radius.circular(4)),
                          borderSide: BorderSide(
                            width: 1,
                            color: Colors.red,
                          )),
                      focusedErrorBorder: OutlineInputBorder(
                        borderRadius: BorderRadius.all(Radius.circular(4)),
                        borderSide: BorderSide(
                          width: 1,
                          color: Colors.red,
                        ),
                      ),
                      hintText: "Enter address" ?? "",
                    ),
                  ),
                ],
              ),
            ),
            SizedBox(
              height: 15.0,
            ),
          ],
        ),
      ),
    );
  }

于 2021-11-25T18:28:45.193 回答