Corporate Training
Request Demo
Click me
Menu
Let's Talk
Request Demo

Tutorials

 Flutter Form Handling and Validation

15. Flutter Form Handling and Validation

Form handling and validation are critical aspects of building Flutter applications, especially when dealing with user input. In this comprehensive tutorial, we'll explore how to create forms, validate user input, and provide feedback to users when errors occur.

1. Creating a Simple Form

To get started with form handling, we'll create a basic form with a text input field and a submit button.

Step 1: Create a Flutter Project

If you haven't already, create a new Flutter project:
flutter create form_handling_example
 

Step 2: Update'pubspec.yaml'

In your 'pubspec.yaml' file, ensure you have the 'flutter/material.dart' package included:
dependencies:
  flutter:
    sdk: flutter
 

Then run 'flutter pub get' to fetch the dependencies.

Step 3: Create a Simple Form

In the 'lib/main.dart' file, create a simple form:
import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Form Handling and Validation',
      home: FormExample(),
    );
  }
}

class FormExample extends StatefulWidget {
  @override
  _FormExampleState createState() => _FormExampleState();
}

class _FormExampleState extends State {
  final _formKey = GlobalKey();
  String _name = '';

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Simple Form Example'),
      ),
      body: Form(
        key: _formKey,
        child: Padding(
          padding: EdgeInsets.all(16.0),
          child: Column(
            children: [
              TextFormField(
                decoration: InputDecoration(
                  labelText: 'Enter Your Name',
                ),
                validator: (value) {
                  if (value.isEmpty) {
                    return 'Please enter your name';
                  }
                  return null;
                },
                onSaved: (value) {
                  _name = value;
                },
              ),
              SizedBox(height: 16.0),
              ElevatedButton(
                onPressed: _submitForm,
                child: Text('Submit'),
              ),
            ],
          ),
        ),
      ),
    );
  }

  void _submitForm() {
    if (_formKey.currentState.validate()) {
      _formKey.currentState.save();
      // Process form data here
      print('Name: $_name');
    }
  }
}
 

In this code, we create a simple form that collects the user's name. We use a 'GlobalKey' to manage the form's state and validation. The 'TextFormField' widget is used for text input, and we provide validation and saving functions.

Step 4: Run the App

Run your app using 'flutter run'. You should see a form where you can enter your name and submit it. Validation ensures that the name is not empty.

2. Form Validation

Form validation ensures that user input meets specific criteria before it's submitted. In the previous example, we used the 'validator' property of 'TextFormField' for validation.

Example: Adding Validation Rules

Let's add more validation rules to the form:
TextFormField(
  decoration: InputDecoration(
    labelText: 'Email',
  ),
  validator: (value) {
    if (value.isEmpty) {
      return 'Please enter your email address';
    }
    if (!value.contains('@')) {
      return 'Please enter a valid email address';
    }
    return null;
  },
  onSaved: (value) {
    _email = value;
  },
),
 

In this code, we added validation to ensure that the email field is not empty and contains the "@" symbol. You can add similar validation rules for other form fields.

3. Displaying Validation Errors

When validation fails, it's essential to provide feedback to the user. Flutter makes it easy to display validation errors.

Example: Displaying Validation Errors
ElevatedButton(
  onPressed: _submitForm,
  child: Text('Submit'),
),
SizedBox(height: 16.0),
Text(
  _formError ?? '',
  style: TextStyle(color: Colors.red),
),
 
In this code, we added a 'Text' widget below the submit button to display validation errors. We set the '_formError' variable when validation fails:
void _submitForm() {
  if (_formKey.currentState.validate()) {
    _formKey.currentState.save();
    // Process form data here
    print('Name: $_name');
    print('Email: $_email');
  } else {
    setState(() {
      _formError = 'Please correct the errors above.';
    });
  }
}
 

If validation fails, the error message will be displayed in red text.

4. Advanced Form Handling

For more complex forms, you may need to handle different input types, create custom form fields, and manage form state using 'TextEditingController'.

Example: Handling a Date Input
class DateInputExample extends StatefulWidget {
  @override
  _DateInputExampleState createState() => _DateInputExampleState();
}

class _DateInputExampleState extends State {
  final _formKey = GlobalKey();
  DateTime _selectedDate;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Date Input Example'),
      ),
      body: Form(
        key: _formKey,
        child: Padding(
          padding: EdgeInsets.all(16.0),
          child: Column(
            children: [
              TextFormField(
                decoration: InputDecoration(
                  labelText: 'Select a Date',
                ),
                validator: (value) {
                  if (_selectedDate == null) {
                    return 'Please select a date';
                  }
                  return null;
                },
                onTap: () async {
                  final selectedDate = await showDatePicker(
                    context: context,
                    initialDate: DateTime.now(),
                    firstDate: DateTime(2000),
                    lastDate: DateTime(2101),
                  );
                  if (selectedDate != null) {
                    setState(() {
                      _selectedDate = selectedDate;
                    });
                  }
                },
                controller: TextEditingController(
                  text: _selectedDate != null
                      ? DateFormat('yyyy-MM-dd').format(_selectedDate)
                      : '',
                ),
              ),
              SizedBox(height: 16.0),
              ElevatedButton(
                onPressed: _submitForm,
                child: Text('Submit'),
              ),
              SizedBox(height: 16.0),
              Text(
                _formError ?? '',
                style: TextStyle(color: Colors.red),
              ),
            ],
          ),
        ),
      ),
    );
  }

  void _submitForm() {
    if (_formKey.currentState.validate()) {
      _formKey.currentState.save();
      // Process form data here
      print('Selected Date: $_selectedDate');
    } else {
      setState(() {
        _formError = 'Please correct the errors above.';
      });
    }
  }
}
 

In this example, we create a form field for selecting a date. We use 'showDatePicker' to display a date picker dialog. The selected date is displayed in the text input field and validated before submission.

Conclusion:

Handling forms and validation is essential for collecting user input and ensuring its correctness in your Flutter applications. By creating forms, adding validation rules, and providing feedback to users, you can create robust and user-friendly apps that effectively capture and process user data. Experiment with different form types and validation scenarios to meet your app's specific requirements.