简体   繁体   English

DropdownButton选择调用Flutter中其他字段的onValidate函数

[英]DropdownButton selection calls the onValidate functions of other fields in Flutter

Not sure what I'm missing.不知道我错过了什么。 When selecting the value of drop-down, form onVaidate() fired which hence my other fields are showing the error.选择下拉列表的值时,表单onVaidate()被触发,因此我的其他字段显示错误。 How can I stop it?我怎样才能阻止它? Here is the code这是代码

Widget build(BuildContext context) { // return Scaffold( // appBar: AppBar(title: Text("Registration")), // body: Center(child: Text(widget.user.displayName)), // ); Widget build(BuildContext context) { // return Scaffold( // appBar: AppBar(title: Text("Registration")), // body: Center(child: Text(widget.user.displayName)), // );

FirebaseUser user = widget.user;

  return Scaffold(
  key: _scaffoldKey,
  appBar: AppBar(
    title: Text("Registration"),
  ),
  body: SafeArea(
      top: false,
      bottom: false,
      child: Form(
          key: _formKey,
          autovalidate: true,
          child: ListView(
            padding: const EdgeInsets.symmetric(horizontal: 16.0),
            children: <Widget>[
              TextFormField(
                validator: (value) => value.isEmpty ? 'Name is Required' : null,
                decoration: const InputDecoration(
                  icon: const Icon(Icons.person),
                  hintText: 'Enter your first and last name',
                  labelText: 'Name',
                ),
              ),
              TextFormField(
                decoration: const InputDecoration(
                  icon: const Icon(Icons.phone),
                  hintText: 'Enter a phone number',
                  labelText: 'Phone',
                ),
                initialValue: user.phoneNumber,
                enabled: user.phoneNumber == null,
                keyboardType: TextInputType.phone,
                validator: (value) => value.isEmpty ? 'Phone number is Required' : null

                // inputFormatters: [
                //   WhitelistingTextInputFormatter.digitsOnly, 
                // ],
              ),
              TextFormField(
                decoration: const InputDecoration(
                  icon: const Icon(Icons.email),
                  hintText: 'Enter a email address',
                  labelText: 'Email',
                ),
                initialValue: user.email,
                enabled: user.email == null,
                validator: (value) => value.isEmpty ? 'Email is Required' : null,
                keyboardType: TextInputType.emailAddress,
              ),
              TextFormField(
                decoration: const InputDecoration(
                  icon: const Icon(Icons.remove_red_eye),
                  hintText: 'Enter the Password',
                  labelText: 'Password',
                ),
                keyboardType: TextInputType.text,
                obscureText: true,
                validator: (value) => value.isEmpty ? 'Password is Required' : null
              ),  
              FormField(
                builder: (FormFieldState state) {
                  return InputDecorator(
                    decoration: InputDecoration(
                      icon: const Icon(Icons.card_membership),
                      labelText: 'ID Type',
                    ),
                    isEmpty: _profile.govId == null,
                    child: DropdownButtonHideUnderline(
                      child: DropdownButton(
                        value: _profile.govId,
                        isDense: true,
                        onChanged: (String newValue) {
                          setState(() {
                            _profile.govId = newValue;
                            state.didChange(newValue);
                          });
                        },
                        items: _govtIds.map((String value) {
                          return DropdownMenuItem(
                            value: value,
                            child: Text(value),
                          );
                        }).toList(),
                      ),
                    ),
                  );
                },
              ),
              TextFormField(
                decoration: const InputDecoration(
                  icon: const Icon(Icons.confirmation_number),
                  hintText: 'Enter your Governmenr ID number',
                  labelText: 'ID Number',
                ),
                keyboardType: TextInputType.datetime,
                validator: (value) => value.isEmpty ? 'ID Number is Required' : null
              ),
              FormField(
                builder: (FormFieldState state) {
                  return InputDecorator(
                    decoration: InputDecoration(
                      icon: const Icon(Icons.business),
                      labelText: 'Block Info',
                    ),
                    isEmpty: _profile.block == null,
                    child: 
                    
                    // Column(children: [RadioListTile(title: Text("A")),RadioListTile(title: Text("B"))]),
                    
                    
                    // Radio(
                    //   value: 0,
                    //   groupValue: _blocks,
                    //   onChanged: (value){}),
                    
                    DropdownButtonHideUnderline(
                      child: 
                      DropdownButton(
                        value: _profile.block,
                        isDense: true,
                        onChanged: (String newValue) {
                          setState(() {
                            _profile.block = newValue;
                            state.didChange(newValue);
                          });
                        },
                        items: _blocks.map((String value) {
                          return DropdownMenuItem(
                            value: value,
                            child: Text(value),
                          );
                        }).toList(),
                      ),
                    ),
                  );
                },
              ),
               TextFormField(
                decoration: const InputDecoration(
                  icon: const Icon(Icons.home),
                  hintText: 'Enter your Flat number',
                  labelText: 'Flat number',
                ),
                 inputFormatters: [LengthLimitingTextInputFormatter(3)],
                validator: (value) {
                  if (value.isEmpty) {
                    return 'Flat number is Required';
                  } else if (_profile.isValidHouseNumber() == false) {
                    return 'Invalid flat number';
                  } else {
                    return null;
                  }
                },
                keyboardType: TextInputType.number,
                onChanged:(value) {
                  _profile.houseNo = value;
                },
              ),
                Padding(
                padding: EdgeInsets.fromLTRB(38.0, 30.0, 0.0, 0.0),
                child: SizedBox(
                height: 50.0,
                child: FlatButton(
                  // elevation: 5.0,
                  shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(10.0)),
                  color: Colors.green,
                  child: Text('Submit',
                      style: TextStyle(fontSize: 20.0, color: Colors.white)),
                  onPressed: _validateAndSubmit,
                ),
              ))
    ],
  ))),
);

} }

三

Call a method to return null in the validate fucntion all the other fields.在验证功能中调用一个方法返回 null 所有其他字段。 That will clear the validation.这将清除验证。 It's a fix, but doesn't solve the problem.这是一个修复,但不能解决问题。

There seems to be nothing wrong with the code above, can you add the code for the other fields too?上面的代码好像没什么问题,能不能把其他字段的代码也加一下?

EDIT:编辑:

The reason all the other fields validate is because of the autovalidate: true property of the parent Form widget.所有其他字段验证的原因是父表单小部件的autovalidate: true属性。 Remove it and wrap each TextFormField with a Form with different keys .删除它并使用具有different keys的 Form 包装每个 TextFormField 。

For example, your TextFormField should look as follows:例如,您的TextFormField应如下所示:

Form(
  key: _formKey[0],
  child: TextFormField(
    validator: (value) => value.isEmpty ? 'Name is Required' : null,
    decoration: const InputDecoration(
      icon: const Icon(Icons.person),
      hintText: 'Enter your first and last name',
      labelText: 'Name',
    ),
  ),
),

Wrap it with a Form, _formKey is declared as用表单包裹它,_formKey 被声明为

List<GlobalObjectKey<FormState>> _formKey = new List(number_of_keys);

Call the respective setState like so:像这样调用相应的 setState:

_formKey[position].currentState.setState((){});

And don't forget to remove the parent Form widget.并且不要忘记删除父表单小部件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM