首页 > 解决方案 > 在 Flutter 中使用两个不同的键验证 TextformField

问题描述

我正在尝试TextFormField使用单个 _formkey 快速验证两个小部件(一个用于电子邮件,另一个用于密码)中的两个不同的 s。它给了我这个错误:多个小部件使用相同的 GlobalKey。所以定义了两个 _formkey 但问题是 Flutter 表单验证器不会同时验证:

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,
              ),
            ),
          ),
        ),
      ],
    );
  }

接着 :

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

标签: flutterdart

解决方案


请记住,您Form在小部件树中需要一个上述小部件。因此,您可以使用 _formKeyTextFormField在 Widget Tree 中验证以下多个。

修改后的代码


   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

推荐阅读