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.
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.
A basic form with:
Name input field
Email input field
A submit button
Validation for both fields
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.
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'),
)
],
),
),
),
);
}
}
We start by running the Flutter app with the basic structure:
main()
launches the app.
MyApp
sets up the theme and the home page.
final _formKey = GlobalKey<FormState>();
This key helps Flutter keep track of the form’s state. It’s needed to run validation.
final _nameController = TextEditingController();
final _emailController = TextEditingController();
These controllers allow us to access the text in the input fields later if needed.
Form(
key: _formKey,
child: Column(...)
)
The Form
widget wraps our input fields. This lets us manage them together.
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.
ElevatedButton(
onPressed: _submitForm,
child: Text('Submit'),
)
When the button is pressed, the _submitForm()
function is called.
ScaffoldMessenger.of(context).showSnackBar(...)
If the form is valid, we show a temporary message saying the form was submitted.
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.
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.
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
.
Try adding more fields like:
Password (with obscured text)
Phone number (with number input type)
Dropdown or Radio Buttons
Thank you for visiting! Enjoy exploring our diverse collection of blogs, crafted with passion and insight to inspire and inform. Happy reading!