Forms in Flutter (Validator and UI)

How to create a form Widget with validators in 3 simple steps
I. C8 Global key in a Stateful Widget
II. Add Validator to TextFormField Widget
III. With Form Key, see Current State and Invoke the validate method
Step I: C8 Global key in a Stateful Widget
class MyCustomFormState extends State<MyCustomForm> {
  final _formKey = GlobalKey<FormState>();
  @override
  Widget build(BuildContext context) {
    return Form(
      key: _formKey,
      child: HomePage());}}
Step II: Add Validator to TextFormField Widget
TextFormField(
  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 method
RaisedButton(
  onPressed: () {
    if (_formKey.currentState.validate()) {
      Scaffold.of(context).showSnackBar(SnackBar(content: Text('Do some processing'))); }},
  child: Text('Submit'),);
Other Widget for Forms
Most app would have forms for user to input data.  As such, it is common to come across the following elements.

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

Popular posts from this blog

Flutter Widget 101 Part 1 (Basic of Flutters, Layouts, Rows and Columns)

Setting up Terminal in Android Studio for Flutter and Bash Profile (For Mac)

Flutter Widget 101 Part 5 (Snackbars, Context, Builder and Key)