Hello friends,
In this article I am gonna show you how you can do Form Validation in a very simple way in Flutter.
Below is the demo of the app we are going to build
App Demo
Watch Video Tutorial
Explanation
Here in this demo, I will have two TextformField and a Button and we will validate them on the press of the button. First we have to wrap the fields inside a “Form” Widget. There is a ‘validator’ function available for all fields inside the “Form”. The ‘validator’ function will return an anonymous function with value of the widget. You can have your won validation inside the function. Then we will create a form key of type GlobalKey<FormState> which will identify a particular form. Then we are going to call formKey.currentState.validate() to validate all the widgets inside the form. If all the widgets are validated, the validate() function will return true else false. There is another function in the formKey to save the values of the form. So when we call formKey.currentState.save(), the onSaved function of each widget gets called.
Let’s get to the code now.
I am gonna show everything at once. here is the whole code
Complete Code
import 'package:flutter/material.dart'; class FormScreen extends StatefulWidget { FormScreen(); @override State<StatefulWidget> createState() { return _FormScreenState(); } } class _FormScreenState extends State<FormScreen> { String name; String age; final formKey = new GlobalKey<FormState>(); validateFormAndSave() { print("Validating Form..."); if (formKey.currentState.validate()) { print("Validation Successful"); formKey.currentState.save(); print('Name $name'); print('Age $age'); } else { print("Validation Error"); } } @override Widget build(BuildContext context) { return new Scaffold( appBar: new AppBar( title: new Text('Flutter Form Demo'), ), body: Form( key: formKey, child: Padding( padding: EdgeInsets.all(10.0), child: new Container( child: new Column( mainAxisAlignment: MainAxisAlignment.start, mainAxisSize: MainAxisSize.min, verticalDirection: VerticalDirection.down, children: <Widget>[ TextFormField( keyboardType: TextInputType.text, decoration: InputDecoration(labelText: "Name"), validator: (val) => val.length == 0 ? "Enter Name" : null, onSaved: (val) => name = val, ), TextFormField( keyboardType: TextInputType.number, decoration: InputDecoration(labelText: "Age"), validator: (val) => val.length == 0 ? "Enter Age" : null, onSaved: (val) => age = val, ), RaisedButton( child: Text("Save"), onPressed: validateFormAndSave, ) ]), ), ), ), ); } }
All good.
Please leave your valuable comments below.
Thanks for reading…
This is short and clear,