Google Advertisement

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

Google Advertisement
πŸ”₯ Read with Full Features on Our Website

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.

Published on 04 May 2025
By Vandu

Blog 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

πŸ”₯ Read with Full Features on Our Website

A basic form with:


🧱 Step 1: Create a New Flutter Project

Google Advertisement

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:

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();
 
Google Advertisement

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:


πŸš€ 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


πŸ’‘ Next Steps

Try adding more fields like:

❀️ Like πŸ’¬ Comment πŸ”— Share
Google Advertisement
πŸ‘‰ View Full Version on Main Website β†—
Google Advertisement
πŸ‘‰ Read Full Article on Website