Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to validate dropdown button in flutter? [closed]

Tags:

flutter

I'm new to flutter development. I'm trying to validate form with drop down but could not. I followed this link for drop down validation. https://github.com/flutter/flutter/issues/6422#issuecomment-262337023

The drop down is being auto validated.

like image 387
KURRU HEM Avatar asked Oct 22 '18 09:10

KURRU HEM


4 Answers

Try using DropdownButtonFormField wrapping inside Form

Ex:

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
                  });
                }
              },
            )
          ],
        ),
      ),
    );
  }
}
like image 70
Favas Kv Avatar answered Sep 19 '22 18:09

Favas Kv


validator: (value) {
if (value == null) {
    return 'Relationship is required';
}
},

try this, this is working form me, two things have to note: 1) dont have a return null and 2) instead this: if(value.isEmpty) use this: if(value == null)

like image 34
AbHi PoOjary Avatar answered Sep 19 '22 18:09

AbHi PoOjary


You should most probably make use of StatefulWidget and it's setState method.

Example:

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"),
          ),
        ]));
  }
like image 20
Raj Yadav Avatar answered Sep 18 '22 18:09

Raj Yadav


Just Simply Add this dropdown to your code and simply import flutter_form_builder to your code.

   List<String> _type = <String>[
        'License/Registered',
        'UN-Registered',
      ]



    FormBuilder(
          autovalidate: true,
          child: FormBuilderCustomField(
              attribute: "Identification type",
              validators: [FormBuilderValidators.required()],
              formField: FormField(
                builder: (FormFieldState<dynamic> field) {
                  return InputDecorator(
                    decoration: InputDecoration(
                      prefixIcon: Icon(Icons.location_on),
                      labelText: 'Select Personal Identification type',
                      errorText: field.errorText,
                    ),
                    isEmpty: type == '',
                    child: new DropdownButtonHideUnderline(
                      child: new DropdownButton(
                        value: type,
                        isDense: true,
                        onChanged: (String newValue) {
                          setState(() {
                            type = newValue;
                            _dropDownValue = newValue;
                            field.didChange(newValue);
                          });
                        },
                        items: _type.map(
                          (String value) {
                            return new DropdownMenuItem(
                              value: value,
                              child: new Text(value),
                            );
                          },
                        ).toList(),
                      ),
                    ),
                  );
                },
              )),
        );
like image 25
Rutvik Gumasana Avatar answered Sep 16 '22 18:09

Rutvik Gumasana