Learn/Forms & Input/Form Widget & Validation

Form Widget & Validation

Build validated forms

6 min~4 min read+35 FX

You can read this lesson publicly. Sign in to unlock exercises, quiz, and FX progress tracking.

Table of Contents

  1. 1. Common Validators
  2. 2. Validation Strategy
  3. 3. This Lesson In Simple Words
  4. 4. Your level focus
  5. 5. One practical habit
  6. 6. Deep Understanding Guide
  7. 7. Why this lesson matters
  8. 8. Study flow for better retention
  9. 9. Quick Glossary

Having trouble? AI is here to help

Ask context-aware questions about this lesson. Free plan: 5 questions/day. Upgrade to Premium for higher daily limits.

Use the AI button at the bottom of the screen

Form Widget

The Form widget groups multiple input fields together and provides built-in validation capabilities. It uses a GlobalKey of type FormState to let you trigger validation and save on all fields at once, so you do not have to check each field individually.

dart
1class LoginForm extends StatefulWidget {
2 @override
3 _LoginFormState createState() => _LoginFormState();
4}
5
6class _LoginFormState extends State<LoginForm> {
7 final _formKey = GlobalKey<FormState>();
8 String _email = '';
9 String _password = '';
10
11 @override
12 Widget build(BuildContext context) {
13 return Form(
14 key: _formKey,
15 child: Column(
16 children: [
17 TextFormField(
18 decoration: InputDecoration(labelText: 'Email'),
19 validator: (value) {
20 if (value == null || value.isEmpty) {
21 return 'Please enter email';
22 }
23 if (!value.contains('@')) {
24 return 'Please enter a valid email';
25 }
26 return null; // Valid
27 },
28 onSaved: (value) => _email = value!,
29 ),
30
31 TextFormField(
32 decoration: InputDecoration(labelText: 'Password'),
33 obscureText: true,
34 validator: (value) {
35 if (value == null || value.length < 8) {
36 return 'Password must be at least 8 characters';
37 }
38 return null;
39 },
40 onSaved: (value) => _password = value!,
41 ),
42
43 ElevatedButton(
44 onPressed: _submitForm,
45 child: Text('Login'),
46 ),
47 ],
48 ),
49 );
50 }
51
52 void _submitForm() {
53 if (_formKey.currentState!.validate()) {
54 _formKey.currentState!.save();
55 print('Email: $_email, Password: $_password');
56 }
57 }
58}

Common Validators

Validators are functions that receive the current field value and return either an error message string or null if the value is acceptable. You can create reusable validator functions and apply them across multiple forms in your app.

dart
1// Email validator
2String? validateEmail(String? value) {
3 if (value == null || value.isEmpty) {
4 return 'Email is required';
5 }
6 final emailRegex = RegExp(r'^[\w-\.]+@[\w-]+\.[a-z]{2,}$');
7 if (!emailRegex.hasMatch(value)) {
8 return 'Enter a valid email';
9 }
10 return null;
11}
12
13// Password validator
14String? validatePassword(String? value) {
15 if (value == null || value.isEmpty) {
16 return 'Password is required';
17 }
18 if (value.length < 8) {
19 return 'Password must be at least 8 characters';
20 }
21 if (!value.contains(RegExp(r'[A-Z]'))) {
22 return 'Password must contain uppercase letter';
23 }
24 return null;
25}

Validation Strategy

Validation should happen in layers:

  • client-side: immediate format and completeness checks
  • server-side: source-of-truth business and security checks

Client validation improves UX, but it is not a security boundary. Always validate again on the backend.

Form Reliability Checklist

  • Every required field has clear validation messaging.
  • Submit button behavior handles loading and duplicate taps.
  • Validation messages are specific, not generic failure text.
  • Successful submit and failure submit states are both handled clearly.

This Lesson In Simple Words

Build validated forms. Widgets are reusable UI blocks. You combine them like LEGO pieces to build screens.

Your level focus

Connect each concept to real app features you can build.

One practical habit

Sketch the widget tree first, then code from top to bottom.

Deep Understanding Guide

Why this lesson matters

Most Flutter productivity comes from understanding layout rules and composing widgets cleanly.

Study flow for better retention

  1. Map the lesson to one screen, one user action, and one expected output.
  2. When a UI bug appears, inspect constraints and parent-child relations before changing random values.
  3. If you can choose between two approaches and explain why, you are improving.

Common Mistakes To Avoid

  • Nesting too many widgets without extracting reusable pieces.
  • Ignoring constraints and guessing with random SizedBox heights.
  • Using one giant build method for unrelated UI sections.
  • Putting heavy calculations directly in build methods.

Practice Sprint (15-25 Minutes)

  • Before running sample code, predict output and behavior in one sentence.
  • Build one card layout with Row/Column and rebuild it using Stack for comparison.
  • Split a large widget into 3 smaller widgets with clear responsibilities.
  • Use const constructors where possible and observe rebuild behavior.
  • Complete the required exercises without using hints on the first attempt.
  • Answer this question out loud before checking quiz options: "What does a validator return when input is valid?".

Quick Glossary

  • widget: A reusable UI building block in Flutter.
  • state: Data that can change and update what the user sees.
  • build: The method that describes UI for the current state.
  • validation: Checks that confirm input is correct before processing.

Code Comprehension Drill

  • State the purpose of the code block in one line before reading details.
  • Mark inputs, state changes, and final output.
  • Change one small value and predict what should happen before running.
  • Run again and compare your prediction with actual behavior.

Lesson Completion Checklist

  • I can explain "Form Widget & Validation" in simple words without reading notes.
  • I can describe one real app situation where this concept is required.
  • I know at least one mistake to avoid: Nesting too many widgets without extracting reusable pieces.
  • I can modify one code sample and correctly predict the behavior change.
  • I can finish required exercises with understanding, not trial-and-error guesses.

Frequently Asked Questions

What does a validator return when input is valid?

Validators return null for valid input, or an error message string for invalid input.

What method triggers form validation?

GlobalKey<FormState> provides access to validate() through currentState.

What widget should you use inside a Form instead of TextField?

TextFormField works with Form widget to enable validation and save functionality.

What does formKey.currentState!.save() do?

save() triggers the onSaved callback on every TextFormField in the form, storing their values.

Suggest Improvement

Something seems incorrect, unclear, or missing? Let us know.

About The Author

FlutterCraft editorial lessons are reviewed by experienced Flutter developers and updated to stay aligned with modern Flutter and Dart best practices.

Reference docs: Flutter Documentation, Dart Language Tour, and official package documentation where relevant.

Sign in to continue with exercises and quiz for this lesson.

Sign In to Continue