My Blog

My WordPress Blog

My Blog

My WordPress Blog

Form Validation Example

This example demonstrates how to create a form with validation using TextFormField and GlobalKey.

dartCopy codeimport 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
return MaterialApp(
  title: 'Form Validation',
  theme: ThemeData(primarySwatch: Colors.blue),
  home: RegistrationForm(),
);
} } class RegistrationForm extends StatefulWidget { @override _RegistrationFormState createState() => _RegistrationFormState(); } class _RegistrationFormState extends State<RegistrationForm> { final _formKey = GlobalKey<FormState>(); String? _name; String? _email; @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: &#91;
          TextFormField(
            decoration: InputDecoration(labelText: 'Name'),
            validator: (value) {
              if (value == null || value.isEmpty) {
                return 'Please enter your name';
              }
              return null;
            },
            onSaved: (value) =&gt; _name = value,
          ),
          TextFormField(
            decoration: InputDecoration(labelText: 'Email'),
            validator: (value) {
              if (value == null || value.isEmpty) {
                return 'Please enter your email';
              } else if (!RegExp(r'^&#91;^@]+@&#91;^@]+\.&#91;^@]+').hasMatch(value)) {
                return 'Please enter a valid email';
              }
              return null;
            },
            onSaved: (value) =&gt; _email = value,
          ),
          SizedBox(height: 20),
          ElevatedButton(
            onPressed: () {
              if (_formKey.currentState!.validate()) {
                _formKey.currentState!.save();
                // Process the data
                ScaffoldMessenger.of(context).showSnackBar(
                  SnackBar(content: Text('Name: $_name, Email: $_email')),
                );
              }
            },
            child: Text('Submit'),
          ),
        ],
      ),
    ),
  ),
);
} }
Form Validation Example

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top