简体   繁体   English

Flutter - 验证下拉值

[英]Flutter - Validate Dropdown value

I'm trying to validate user input in the dropdown button , but it doesn't work as it should plus the autovalidate is deprecated makes me even more confused.我正在尝试验证下拉按钮中的用户输入,但它无法正常工作,而且自动验证已被弃用,这让我更加困惑。 And I need to validate another textfield if user selected one of the dropdown list.如果用户选择了下拉列表之一,我需要验证另一个文本字段

Here is the code for my dropdown button and the textfield(ignore the commented codes):这是我的下拉按钮和文本字段的代码(忽略注释代码):

  //textfield controller
  TextEditingController sickController = TextEditingController();

  //Dropdown list values
  final items = ['Healthy', 'Unhealthy'];

...

                  //Dropdown List | Health
                  Container(
                    width: scrwidth * 0.8,
                    height: scrheight / 16,
                    decoration: const BoxDecoration(
                        color: Colors.white,
                        borderRadius: BorderRadius.all(
                          Radius.circular(8),
                        ),
                        boxShadow: [
                          BoxShadow(
                            color: Colors.black54,
                            blurRadius: 10,
                            offset: Offset(2, 2),
                          )
                         ]
                        ),
                    child: Row(
                      children: [
                        SizedBox(
                          width: scrwidth / 18,
                        ),
                        Expanded(
                          child: Padding(
                            padding: const EdgeInsets.all(8.0),
                            child: DropdownButtonHideUnderline(
                              child: DropdownButtonFormField<String>(
                                // key: _sickkey,
                                // autovalidateMode: _autovalidate,
                                decoration: const InputDecoration(
                                  border: InputBorder.none,
                                  isDense: true,
                                ),
                                icon: const Icon(
                                  Icons.arrow_drop_down,
                                  color: Colors.black54,
                                ),
                                hint: const Text(
                                  "Health",
                                  style: TextStyle(
                                      fontFamily: "Ubuntu",
                                      fontWeight: FontWeight.w500),
                                ),
                                isExpanded: true,
                                value: value,
                                // validator: (value) =>
                                //     value == null ? 'field required' : null,
                                items: items.map(buildMenuItem).toList(),
                                onChanged: (value) =>
                                    setState(() {
                                  this.value = value;
                                  if (this.value == "Unhealthy") {
                                    isVisible = true;
                                  } else {
                                    isVisible = false;
                                  }
                                }),
                              ),
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                  //Sickness Textfield
                  Visibility(
                    child: Container(
                      width: scrwidth * 0.8,
                      height: scrheight / 16,
                      margin: const EdgeInsets.only(top: 8),
                      decoration: const BoxDecoration(
                        color: Colors.white,
                        borderRadius: BorderRadius.all(Radius.circular(12)),
                        boxShadow: [
                          BoxShadow(
                            color: Colors.black26,
                            blurRadius: 10,
                            offset: Offset(2, 2),
                          )
                        ],
                      ),
                      child: Row(
                        children: [
                          SizedBox(
                            width: scrwidth / 6,
                            child: Icon(
                              Icons.medication,
                              color: primary,
                              size: scrwidth / 15,
                            ),
                          ),
                          Expanded(
                            child: Padding(
                              padding: EdgeInsets.only(
                                right: scrwidth / 12,
                              ),
                              child: TextFormField(
                                controller: sickController,
                                enableSuggestions: false,
                                autocorrect: false,
                                decoration: InputDecoration(
                                  contentPadding: EdgeInsets.symmetric(
                                    vertical: scrheight / 50,
                                  ),
                                  border: InputBorder.none,
                                  hintText: "State your sickness",
                                ),
                              ),
                            ),
                          )
                        ],
                      ),
                    ),
                    visible: isVisible,
                  ),

Here is the slide button that will send all the data to the internet to be stored in database using php API:这是将所有数据发送到互联网以使用 php API 存储在数据库中的滑动按钮:

                         onSubmit: () async {
                            print(name +
                                " (" +
                                user.lg_username! +
                                ")" +
                                " checked in on " +
                                DateFormat('y-M-d HH:mm:ss a')
                                    .format(DateTime.now()) +
                                " at " +
                                location);
                            print(
                                //Health? If Unhealthy, State sickness
                                 );
                            Timer(const Duration(seconds: 3), () {
                              key.currentState!.reset();
                            });
                          },
                        );

在此处输入图像描述

How do I save the input from the dropdown right before user can interact the slide button mentioned above, without sending a null value from both dropdown and textfield?如何在用户可以交互上述滑动按钮之前从下拉列表中保存输入,而不从下拉列表和文本字段中发送空值?

Use validator in each FormField and validate on FormState .在每个FormField中使用validator并在FormStatevalidate

final GlobalKey<FormState> _formKey = GlobalKey<FormState>();

Form(
  key: _formKey,
  child: Column(
    children: <Widget>[
      TextFormField(
        validator: (String? value) {
          if (value == null || value.isEmpty) {
            return 'Error text';
          }
          return null;
        },
      ),
      ElevatedButton(
        onPressed: () {
          if (_formKey.currentState!.validate()) {
            // valid, send
          }
        },
        child: const Text('Submit'),
      ),
    ],
  ),
);

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

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