Forms in Flutter (Validator and UI)
How to create a form Widget with validators in 3 simple steps
Most app would have forms for user to input data. As such, it is common to come across the following elements.I. C8 Global key in a Stateful WidgetII. Add Validator to TextFormField WidgetIII. With Form Key, see Current State and Invoke the validate methodStep I: C8 Global key in a Stateful Widget
class MyCustomFormState extends State<MyCustomForm> {final _formKey = GlobalKey<FormState>();@overrideWidget build(BuildContext context) {return Form(key: _formKey,child: HomePage());}}
Step II: Add Validator to TextFormField WidgetTextFormField(validator: (form_value) {if (form_value.isEmpty) {return 'Please enter some text'}return null; },);
Step III: With Form Key, see Current State and Invoke the validate methodRaisedButton(onPressed: () {if (_formKey.currentState.validate()) {Scaffold.of(context).showSnackBar(SnackBar(content: Text('Do some processing'))); }},child: Text('Submit'),);Other Widget for Forms
Dropdown List/Box (DropdownButton Class)
Dropdown List/Box is known as Dropdown Button in Flutter.
Separately outside dropdownButton(), in a Var:
Var _list = ['cat', 'dog'];
items: _list.map((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(value),
);
}).toList()
In "item" of dropdownbutton() [Official Doc]:
child: DropdownButton<String> (
hint: Text("Type of Task"),
value: dropdownValue,
onChanged: (String newValue) {
setState(() {
dropdownValue = newValue;
});
},
items: <String>['one','two','three','four'].map<DropdownMenuItem<String>>((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(value),
);
}).toList(),
),
Expanded Widget
Make a child fill all available spaces and divide available spaces between multiple children (if any)
Comments
Post a Comment