Apps often require users to enter information into a text field. For example, you might require users to log in with an email address and password combination.
To make apps secure and easy to use, check whether the information the user has provided is valid. If the user has correctly filled out the form, process the information. If the user submits incorrect information, display a friendly error message letting them know what went wrong.
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 66 67 68 69 70 71 72 73 74 75 | import 'package:flutter/material.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { final appTitle = 'Form Validation Demo'; return MaterialApp( title: appTitle, home: Scaffold( appBar: AppBar( title: Text(appTitle), ), body: MyCustomForm(), ), ); } } // Create a Form widget. class MyCustomForm extends StatefulWidget { @override MyCustomFormState createState() { return MyCustomFormState(); } } // Create a corresponding State class. // This class holds data related to the form. class MyCustomFormState extends State<MyCustomForm> { // Create a global key that uniquely identifies the Form widget // and allows validation of the form. // // Note: This is a GlobalKey<FormState>, // not a GlobalKey<MyCustomFormState>. final _formKey = GlobalKey<FormState>(); @override Widget build(BuildContext context) { // Build a Form widget using the _formKey created above. return Form( key: _formKey, child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ TextFormField( validator: (value) { if (value.isEmpty) { return 'Please enter some text'; } return null; }, ), Padding( padding: const EdgeInsets.symmetric(vertical: 16.0), child: RaisedButton( onPressed: () { // Validate returns true if the form is valid, or false // otherwise. if (_formKey.currentState.validate()) { // If the form is valid, display a Snackbar. Scaffold.of(context) .showSnackBar(SnackBar(content: Text('Processing Data'))); } }, child: Text('Submit'), ), ), ], ), ); } } |
If you like FreeWebMentor and you would like to contribute, you can write an article and mail your article to [email protected] Your article will appear on the FreeWebMentor main page and help other developers.