Creating Forms and Validation with Flutter


Flutter, especially in the mobile app development process, offers high performance and ease of development. It allows you to quickly create your designs and use UI components efficiently. In this article, we will discuss form creation and validation processes with Flutter.

Creating a Form with Flutter

To create a form, we will first use the Form and TextFormField widgets. The Form widget is used to group form elements, while the TextFormField is used to receive text input from the user.

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text('Form Example')),
        body: MyForm(),
      ),
    );
  }
}

class MyForm extends StatefulWidget {
  @override
  _MyFormState createState() => _MyFormState();
}

class _MyFormState extends State {
  final _formKey = GlobalKey();

  @override
  Widget build(BuildContext context) {
    return 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;
            },
          ),
          TextFormField(
            decoration: InputDecoration(labelText: 'Email'),
            validator: (value) {
              if (value == null || value.isEmpty) {
                return 'Please enter an email';
              }
              if (!RegExp(r'^[^@]+@[^@]+\.[^@]+').hasMatch(value)) {
                return 'Invalid email address';
              }
              return null;
            },
          ),
          ElevatedButton(
            onPressed: () {
              if (_formKey.currentState!.validate()) {
                ScaffoldMessenger.of(context)
                    .showSnackBar(SnackBar(content: Text('Form is valid')));
              }
            },
            child: Text('Submit'),
          ),
        ],
      ),
    );
  }
}

Using Validation in the Form

To validate form elements, we used the validator parameter inside each TextFormField. By checking the inputs from the user, we convey appropriate messages. If the input is valid, the form is allowed to be submitted; otherwise, the user sees an error message.

Conclusion

Creating forms and performing validation with Flutter is quite simple. By following the specified steps, you can develop user-friendly forms. Working with valid data not only increases your application's quality but also positively affects the user experience. These conveniences offered by Flutter will speed up your mobile application development process.