logologo
  • AI Tools

    DB Query GeneratorMock InterviewResume BuilderLearning Path GeneratorCheatsheet GeneratorAgentic Prompt GeneratorCompany ResearchCover Letter Generator
  • XpertoAI
  • MVP Ready
  • Resources

    CertificationsTopicsExpertsCollectionsArticlesQuestionsVideosJobs
logologo

Elevate Your Coding with our comprehensive articles and niche collections.

Useful Links

  • Contact Us
  • Privacy Policy
  • Terms & Conditions
  • Refund & Cancellation
  • About Us

Resources

  • Xperto-AI
  • Certifications
  • Python
  • GenAI
  • Machine Learning

Interviews

  • DSA
  • System Design
  • Design Patterns
  • Frontend System Design
  • ReactJS

Procodebase © 2024. All rights reserved.

Level Up Your Skills with Xperto-AI

A multi-AI agent platform that helps you level up your development skills and ace your interview preparation to secure your dream job.

Launch Xperto-AI

Working with Forms and User Input in Flutter

author
Generated by
Nitish Kumar Singh

21/09/2024

Flutter

Sign in to read full article

Flutter offers a rich set of widgets and tools that help developers create responsive and interactive applications. One of the essential features of any app is the ability to handle user input through forms. In this blog, we'll explore how to implement forms in Flutter, manage user input, and validate that input to ensure it meets our criteria.

Setting Up a Simple Form in Flutter

To demonstrate working with forms, let's create a simple registration form that captures a user's name, email, and password. We will also validate the input to ensure it meets specific requirements.

Step 1: Create a New Flutter Project

If you haven't already, create a new Flutter project by running:

flutter create registration_form

Then navigate into your project:

cd registration_form

Step 2: Define the Form Structure

Open the lib/main.dart file, and set up the basic structure of your app. We'll create a Form with TextFormField widgets for each input field. Here's how we can do that:

import 'package:flutter/material.dart'; void main() { runApp(MyApp()); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( home: RegistrationForm(), ); } } class RegistrationForm extends StatefulWidget { @override _RegistrationFormState createState() => _RegistrationFormState(); } class _RegistrationFormState extends State<RegistrationForm> { final _formKey = GlobalKey<FormState>(); String? _name, _email, _password; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('Registration Form'), ), body: Padding( padding: const EdgeInsets.all(16.0), child: Form( key: _formKey, child: Column( children: [ TextFormField( decoration: InputDecoration(labelText: 'Name'), validator: (value) { if (value == null || value.isEmpty) { return 'Please enter your name'; } return null; }, onSaved: (value) { _name = value!; }, ), TextFormField( decoration: InputDecoration(labelText: 'Email'), validator: (value) { if (value == null || value.isEmpty) { return 'Please enter your email'; } else if (!RegExp(r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$').hasMatch(value)) { return 'Please enter a valid email address'; } return null; }, onSaved: (value) { _email = value!; }, ), TextFormField( decoration: InputDecoration(labelText: 'Password'), obscureText: true, validator: (value) { if (value == null || value.isEmpty) { return 'Please enter your password'; } else if (value.length < 6) { return 'Password must be at least 6 characters long'; } return null; }, onSaved: (value) { _password = value!; }, ), SizedBox(height: 20), ElevatedButton( onPressed: () { if (_formKey.currentState!.validate()) { _formKey.currentState!.save(); // Here you would typically call a backend API or similar print('Name: $_name, Email: $_email, Password: $_password'); } }, child: Text('Submit'), ), ], ), ), ), ); } }

Step 3: Guide Through the Code

  1. GlobalKey<FormState>: The GlobalKey lets Flutter manage the state of the form. It is crucial for validating and saving form data.

  2. TextFormField: Each field takes several parameters:

    • decoration: A way to customize the field's appearance and set a label.
    • validator: A function that checks if the input meets certain criteria; if not, it returns an error message.
    • onSaved: This callback saves the input into a variable when the form is submitted.
  3. ElevatedButton: When the button is pressed, we first check if the form is valid using validate(), and then we save the input data with save().

Running the App

You can now run your app using flutter run. Once it is running, try filling in the fields with different inputs to see the validation messages in action.

Conclusion

In this blog post, we focused on how to create forms in Flutter and handle user input effectively. We explored how to validate inputs and save them when the user submits the form. This is just the beginning; Flutter's flexibility allows for more complex forms and dynamic validation rules that can be tailored to fit various needs. Stay tuned for more articles diving deep into the Flutter ecosystem!

Popular Tags

FlutterFormsUser Input

Share now!

Like & Bookmark!

Related Collections

  • Flutter Development: Build Beautiful Apps

    21/09/2024 | Flutter

Related Articles

  • Enhancing User Experience with Animations and Transitions in Flutter

    21/09/2024 | Flutter

  • Exploring Flutter for Web and Desktop

    21/09/2024 | Flutter

  • Working with Forms and User Input in Flutter

    21/09/2024 | Flutter

  • Networking in Flutter

    21/09/2024 | Flutter

  • Testing Flutter Applications

    21/09/2024 | Flutter

  • Deploying Flutter Apps to App Stores

    21/09/2024 | Flutter

  • Performance Optimization in Flutter Apps

    21/09/2024 | Flutter

Popular Category

  • Python
  • Generative AI
  • Machine Learning
  • ReactJS
  • System Design