Want to validate dropdown in flutter? Try using DropdownButtonFormField wrapping inside Form
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 | 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 }); } }, ) ], ), ), ); } } |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.