DAni M
DAni M

Reputation: 791

Validating TextformField with two different key in Flutter

I'm trying to validate two different TextFormFields in two widgets (One for Email, another one for password) with a single _formkey in a flutter. it gave me this error: Multiple widgets used the same GlobalKey. So defined two _formkey but the problem is Flutter form validators don't validate, simultaneously:

class _RegisterState extends State<Register> {
  String email = "";
  String password = "";
  String error = "";
  final _formKey1 = GlobalKey<FormState>();
  final _formKey2 = GlobalKey<FormState>();
   

  // bool _rememberMe = false;

  Widget _buildEmailTF() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        Text(
          'Email',
          style: kLabelStyle,
        ),
        SizedBox(height: 10.0),
        Form(
          key: _formKey1,
          child: Container(
            alignment: Alignment.centerLeft,
            decoration: kBoxDecorationStyle,
            height: 60.0,
            child: TextFormField(
              validator: (value) => value.isEmpty ? "Enter an Email" : null,
              onChanged: (value) {
                setState(() {
                  email = value;
                });
              },
              style: TextStyle(
                color: Colors.white,
                fontFamily: 'OpenSans',
              ),
              decoration: InputDecoration(
                border: InputBorder.none,
                contentPadding: EdgeInsets.only(top: 14.0),
                prefixIcon: Icon(
                  Icons.email,
                  color: Colors.white,
                ),
                hintText: 'Enter your Email',
                hintStyle: kHintTextStyle,
              ),
            ),
          ),
        ),
      ],
    );
  }

  Widget _buildPasswordTF() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        Text(
          'Password',
          style: kLabelStyle,
        ),
        SizedBox(height: 10.0),
        Form(
          key: _formKey2,
          child: Container(
            alignment: Alignment.centerLeft,
            decoration: kBoxDecorationStyle,
            height: 60.0,
            child: TextFormField(
              validator: (value) =>
                  value.length < 6 ? "More than 6 Character" : null,
              onChanged: (value) {
                setState(() {
                  password = value;
                });
              },
              obscureText: true,
              style: TextStyle(
                color: Colors.white,
                fontFamily: 'OpenSans',
              ),
              decoration: InputDecoration(
                border: InputBorder.none,
                contentPadding: EdgeInsets.only(top: 14.0),
                prefixIcon: Icon(
                  Icons.lock,
                  color: Colors.white,
                ),
                hintText: 'Enter your Password',
                hintStyle: kHintTextStyle,
              ),
            ),
          ),
        ),
      ],
    );
  }

and then :

onPressed: () async {
          if (_formKey1.currentState.validate() &&
              _formKey2.currentState.validate()) {
            dynamic result =
                await _auth.signUpWithEmailandPassword(email, password);
            if (result == null) {
              setState(() => error = "Something is wrong");
            }
          }
        },

Upvotes: 0

Views: 1469

Answers (1)

DIVYANSHU SAHU
DIVYANSHU SAHU

Reputation: 1215

Just remember that you need one Form Widget above in the widget Tree. And thus you can use the _formKey to validate multiple TextFormField below in the Widget Tree.

Modified Code


   class _RegisterPageState extends State<RegisterPage> {
    String email = "";
    String password = "";
    String error = "";
    final _formKey1 = GlobalKey<FormState>();
    // final _formKey2 = GlobalKey<FormState>();
  
    @override
    Widget build(BuildContext context) {
      return Scaffold(
        backgroundColor: Colors.white,
        body: Form(
          key: _formKey1,
          child: Container(
            child: Column(
              children: [
                _buildEmailTF(),
                SizedBox(
                  height: 20,
                ),
                _buildPasswordTF(),
                FlatButton(
                    onPressed: () async {
                      if (_formKey1.currentState.validate()) {
                        // dynamic result = await _auth.signUpWithEmailandPassword(
                        //     email, password);
                        // if (result == null) {
                        //   setState(() => error = "Something is wrong");
                        // }
                        print('DOne Working');
                      }
                    },
                    child: Text(
                      'Done',
                    ))
              ],
            ),
          ),
        ),
      );
    }
  
    // bool _rememberMe = false;
  
    Widget _buildEmailTF() {
      return Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Text(
            'Email',
          ),
          SizedBox(height: 10.0),
          Container(
            alignment: Alignment.centerLeft,
            height: 60.0,
            child: TextFormField(
              validator: (value) => value.isEmpty ? "Enter an Email" : null,
              onChanged: (value) {
                setState(() {
                  email = value;
                });
              },
              style: TextStyle(
                color: Colors.white,
                fontFamily: 'OpenSans',
              ),
              decoration: InputDecoration(
                border: InputBorder.none,
                contentPadding: EdgeInsets.only(top: 14.0),
                prefixIcon: Icon(
                  Icons.email,
                  color: Colors.white,
                ),
                hintText: 'Enter your Email',
              ),
            ),
          ),
        ],
      );
    }
  
    Widget _buildPasswordTF() {
      return Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Text(
            'Password',
          ),
          SizedBox(height: 10.0),
          Container(
            alignment: Alignment.centerLeft,
            height: 60.0,
            child: TextFormField(
              validator: (value) =>
                  value.length < 6 ? "More than 6 Character" : null,
              onChanged: (value) {
                setState(() {
                  password = value;
                });
              },
              obscureText: true,
              style: TextStyle(
                color: Colors.white,
                fontFamily: 'OpenSans',
              ),
              decoration: InputDecoration(
                border: InputBorder.none,
                contentPadding: EdgeInsets.only(top: 14.0),
                prefixIcon: Icon(
                  Icons.lock,
                  color: Colors.white,
                ),
                hintText: 'Enter your Password',
              ),
            ),
          ),
        ],
      );
    }
  }

I/flutter (24750): DOne Working

Upvotes: 1

Related Questions