How to Build and Validate Forms in Flutter – Simple Example for Beginners

By Vandu
May 4, 2025

Follow us on


Learn how to design a user input form in Flutter with proper validation using simple code. A perfect guide for Flutter beginners with easy-to-follow steps and explanations.

How to Build and Validate Forms in Flutter – Simple Example for BeginnersBlog Article: Design a Simple Form with Validation in Flutter

👋 Introduction

In many mobile apps, we need to collect user information such as name, email, or password. Flutter makes it easy to build forms using widgets like TextFormField, Form, and validation functions. In this tutorial, we will build a simple Flutter form with input fields and validation, step-by-step.

🎯 What We Will Build

A basic form with:

  • Name input field

  • Email input field

  • A submit button

  • Validation for both fields


🧱 Step 1: Create a New Flutter Project

If you haven’t created a project yet, open your terminal or command prompt and run:

flutter create simple_form_app
cd simple_form_app

Open the project in your favorite IDE like VS Code or Android Studio.


📄 Step 2: Full Code – Simple Form with Validation

Replace everything in lib/main.dart with the following code:

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Simple Form',
      theme: ThemeData(primarySwatch: Colors.blue),
      home: SimpleFormPage(),
    );
  }
}

class SimpleFormPage extends StatefulWidget {
  @override
  _SimpleFormPageState createState() => _SimpleFormPageState();
}

class _SimpleFormPageState extends State<SimpleFormPage> {
  final _formKey = GlobalKey<FormState>(); // Form key to manage form state
  final _nameController = TextEditingController();
  final _emailController = TextEditingController();

  @override
  void dispose() {
    // Clean up the controllers when the widget is disposed.
    _nameController.dispose();
    _emailController.dispose();
    super.dispose();
  }

  void _submitForm() {
    if (_formKey.currentState!.validate()) {
      // If the form is valid, show a success message
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('Form Submitted Successfully!')),
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Simple Form')),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Form(
          key: _formKey, // Assign the form key
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // Name Field
              TextFormField(
                controller: _nameController,
                decoration: InputDecoration(labelText: 'Name'),
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return 'Please enter your name';
                  }
                  return null; // valid input
                },
              ),
              SizedBox(height: 16),

              // Email Field
              TextFormField(
                controller: _emailController,
                decoration: InputDecoration(labelText: 'Email'),
                keyboardType: TextInputType.emailAddress,
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return 'Please enter your email';
                  } else if (!value.contains('@')) {
                    return 'Please enter a valid email';
                  }
                  return null;
                },
              ),
              SizedBox(height: 32),

              // Submit Button
              ElevatedButton(
                onPressed: _submitForm,
                child: Text('Submit'),
              )
            ],
          ),
        ),
      ),
    );
  }
}

🔍 Step-by-Step Explanation

1. Project Setup

We start by running the Flutter app with the basic structure:

  • main() launches the app.

  • MyApp sets up the theme and the home page.

2. Form Key

final _formKey = GlobalKey<FormState>();
 

This key helps Flutter keep track of the form’s state. It’s needed to run validation.

3. TextEditingController

final _nameController = TextEditingController();
final _emailController = TextEditingController();
 

These controllers allow us to access the text in the input fields later if needed.

4. Form Widget

Form(
  key: _formKey,
  child: Column(...)
)
 

The Form widget wraps our input fields. This lets us manage them together.

5. TextFormField with Validation

validator: (value) {
  if (value == null || value.isEmpty) {
    return 'Please enter your name';
  }
  return null;
}
 

This is a validation function. If the input is invalid (like empty), it returns an error string. Otherwise, it returns null, meaning the input is valid.

6. Submit Button

 
ElevatedButton(
  onPressed: _submitForm,
  child: Text('Submit'),
)

When the button is pressed, the _submitForm() function is called.

7. Showing a Success Message

ScaffoldMessenger.of(context).showSnackBar(...)
 

If the form is valid, we show a temporary message saying the form was submitted.


🧪 Output Example

When you run this app:

  • If you leave the fields empty and tap Submit, you will see error messages.

  • If you enter a valid name and email, a message “Form Submitted Successfully!” appears.


🚀 Conclusion

That’s it! You’ve built a working form in Flutter with validation. This is a foundation you can use in real apps like login screens, registration forms, or surveys.

✅ Key Takeaways

  • Use Form and TextFormField for user input in Flutter.

  • Always wrap forms with a GlobalKey<FormState> for validation.

  • Use controllers to get or set field values.

  • Validation is done using simple functions inside validator.


💡 Next Steps

Try adding more fields like:

  • Password (with obscured text)

  • Phone number (with number input type)

  • Dropdown or Radio Buttons


© 2025 Pay18News. All rights reserved.