使用formKey.currentState.reset()重置表单不起作用

时间:2019-07-08 13:40:07

标签: forms validation flutter

我正在创建一个包含电子邮件地址,密码及其提交按钮的表单。当我尝试使用formKey.currentState.reset重置表单时,它不起作用。你能帮我吗

class App extends StatelessWidget{
Widget build(context){
  return MaterialApp(
    title: 'Log Me In!',
    home: Scaffold(
          body: LoginScreen(),
    )
  );
}

}





class LoginScreen extends StatefulWidget {
  LoginScreenState createState() => LoginScreenState();
}

class LoginScreenState extends State<LoginScreen> {
  final formKey = GlobalKey<FormState>();

  Widget build(BuildContext context) {
    return Container(
        margin: EdgeInsets.all(20.0),
        child: Form(
            child: Column(
          children: <Widget>[
            emailField(),
             passwordField(),
             Container(margin: EdgeInsets.only(top: 25.0),),
              submitButton(),
          ],
        )));
  }



Widget submitButton(){

   return RaisedButton(
     child: Text('Submit'),
     color: Colors.blueGrey,
     onPressed: (){
       formKey.currentState.reset();
     },
   );
 }

我希望重新设置电子邮件地址和密码。没有错误消息。

1 个答案:

答案 0 :(得分:1)

我知道您的问题是什么,您需要使用创建的变量来设置key小部件的Form属性。例如。 key: formKey

下面是您的LoginScreenState类的完整代码,可以解决此问题:

class LoginScreenState extends State<LoginScreen> {
  final formKey = GlobalKey<FormState>();

  Widget build(BuildContext context) {
    return Container(
      margin: EdgeInsets.all(20.0),
      child: Form(
        key: formKey, // you missed out on this!!!
        child: Column(
          children: <Widget>[
            emailField(),
            passwordField(),
            Container(margin: EdgeInsets.only(top: 25.0),),
            submitButton(),
          ],
        )
      )
    );
  }

  Widget submitButton(){
    return RaisedButton(
      child: Text('Submit'),
      color: Colors.blueGrey,
      onPressed: (){
        formKey.currentState.reset();
      },
    );
  }
}