如何验证颤动中的下拉按钮?

KUR*_*HEM 19 flutter

我是颤振开发的新手。我正在尝试使用下拉列表验证表单,但不能。我按照此链接进行下拉验证。 https://github.com/flutter/flutter/issues/6422#issuecomment-262337023

下拉正在自动验证。

Fav*_* Kv 33

尝试在Form 中使用DropdownButtonFormField包装

前任:

import 'package:flutter/material.dart';

class FormValidationWithDropdown extends StatefulWidget {
  @override
  _FormValidationWithDropdownState createState() =>
      _FormValidationWithDropdownState();
}

class _FormValidationWithDropdownState
    extends State<FormValidationWithDropdown> {
  final _formKey = GlobalKey<FormState>();
  bool _autovalidate = false;
  String selectedSalutation;
  String name;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Form(
        key: _formKey,
        autovalidate: _autovalidate,
        child: Column(
          children: <Widget>[
            DropdownButtonFormField<String>(
              value: selectedSalutation,
              hint: Text(
                'Salutation',
              ),
              onChanged: (salutation) =>
                  setState(() => selectedSalutation = salutation),
              validator: (value) => value == null ? 'field required' : null,
              items:
                  ['MR.', 'MS.'].map<DropdownMenuItem<String>>((String value) {
                return DropdownMenuItem<String>(
                  value: value,
                  child: Text(value),
                );
              }).toList(),
            ),
            TextFormField(
              decoration: InputDecoration(hintText: 'Name'),
              validator: (value) => value.isEmpty ? 'Name is required' : null,
              onSaved: (value) => name = value,
            ),
            FlatButton(
              child: Text('PROCEED'),
              color: Colors.green,
              onPressed: () {
                if (_formKey.currentState.validate()) {
                  //form is valid, proceed further
                  _formKey.currentState.save();//save once fields are valid, onSaved method invoked for every form fields

                } else {
                  setState(() {
                    _autovalidate = true; //enable realtime validation
                  });
                }
              },
            )
          ],
        ),
      ),
    );
  }
}
Run Code Online (Sandbox Code Playgroud)


小智 6

validator: (value) {
if (value == null) {
    return 'Relationship is required';
}
},
Run Code Online (Sandbox Code Playgroud)

试试这个,这是我的工作方式,有两件事必须注意:1)没有返回 null 和 2)代替这个: if(value.isEmpty) 使用这个: if(value == null)


Raj*_*dav 3

您很可能应该使用StatefulWidget它的setState方法。

例子:

var _formKey = GlobalKey<FormState>();
  String _dropdownError;
  String _selectedItem;

  _validateForm() {
    bool _isValid = _formKey.currentState.validate();

    if (_selectedItem == null) {
      setState(() => _dropdownError = "Please select an option!");
      _isValid = false;
    }

    if (_isValid) {
      //form is valid
    }
  }

  @override
  Widget build(BuildContext context) {
    return Form(
        key: _formKey,
        child: ListView(children: <Widget>[
          TextFormField(validator: (val) {
            if (val.isEmpty) return "This field is required";
            return null;
          }
            //other textformfield properties
          ),
          DropdownButtonHideUnderline(
            child: DropdownButton<String>(
              value: _selectedItem,
              isExpanded: true,
              hint: Text("Select option", maxLines: 1),
              items: ["Option 1", "Option 2", "Option 3"].map((String value) {
                return DropdownMenuItem<String>(
                  value: value,
                  child: new Text(
                    value ?? "",
                    textAlign: TextAlign.left,
                    overflow: TextOverflow.ellipsis,
                    maxLines: 1,
                    softWrap: true,
                  ),
                );
              }).toList(),
              onChanged: (value) {
                setState(() {
                  _selectedItem = value;
                  _dropdownError = null;
                });
              },
            ),
          ),
          _dropdownError == null
              ? SizedBox.shrink()
              : Text(
            _dropdownError ?? "",
            style: TextStyle(color: Colors.red),
          ),
          RaisedButton(
            onPressed: () => _validateForm(),
            child: Text("Submit"),
          ),
        ]));
  }
Run Code Online (Sandbox Code Playgroud)