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
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:
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:
π 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
This key helps Flutter keep track of the form’s state. It’s needed to run validation.
3. TextEditingController
These controllers allow us to access the text in the input fields later if needed.
4. Form Widget
The Form
widget wraps our input fields. This lets us manage them together.
5. TextFormField with Validation
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
When the button is pressed, the _submitForm()
function is called.
7. Showing a Success Message
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.
-
Google Advertisement
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
andTextFormField
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