EXPERIMENT-7

 7a)Design a form with various input fields.

import 'package:flutter/material.dart';

void main() {

  runApp(MyApp());

}

class MyApp extends StatelessWidget {

  @override

  Widget build(BuildContext context) {

    return MaterialApp(

      title: 'User Form',

      home: Scaffold(

        appBar: AppBar(

          title: Text('User Input Form'),

        ),

        body: SingleChildScrollView(

          padding: EdgeInsets.all(16.0),

          child: UserForm(),

        ),

      ),

    );

  }

}

class UserForm extends StatefulWidget {

  @override

  State<UserForm> createState() => _UserFormState();

}

class _UserFormState extends State<UserForm> {

  String? _name;

  String? _email;

  String? _phoneNumber;

  String? _collegeName;

 @override

  Widget build(BuildContext context) {

    return Column(

      crossAxisAlignment: CrossAxisAlignment.start,

      children: [

        Text('Please fill in the form:', style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold)),

        SizedBox(height: 20),

// Name Field

        TextFormField(

          decoration: InputDecoration(

            labelText: 'Name',

            border: OutlineInputBorder(),

            prefixIcon: Icon(Icons.person),

          ),

          onChanged: (value) => _name = value,

        ),

        SizedBox(height: 16),


        // Email Field

        TextFormField(

          decoration: InputDecoration(

            labelText: 'Email ID',

            border: OutlineInputBorder(),

            prefixIcon: Icon(Icons.email),

          ),

          keyboardType: TextInputType.emailAddress,

          onChanged: (value) => _email = value,

        ),

        SizedBox(height: 16),


        // Phone Number Field

        TextFormField(

          decoration: InputDecoration(

            labelText: 'Phone Number',

            border: OutlineInputBorder(),

            prefixIcon: Icon(Icons.phone),

          ),

          keyboardType: TextInputType.phone,

          onChanged: (value) => _phoneNumber = value,

        ),

        SizedBox(height: 16),


        // College Name Field

        TextFormField(

          decoration: InputDecoration(

            labelText: 'College Name',

            border: OutlineInputBorder(),

            prefixIcon: Icon(Icons.school),

          ),

          onChanged: (value) => _collegeName = value,

        ),

        SizedBox(height: 24),


        // Submit Button

        Center(

          child: ElevatedButton(

            onPressed: () {

              showDialog(

                context: context,

                builder: (context) {

                  return AlertDialog(

                    title: Text('Form Submitted'),

                    content: Text('Name: $_name\nEmail: $_email\nPhone: $_phoneNumber\nCollege: $_collegeName'),

                    actions: [

                      TextButton(

                        onPressed: () => Navigator.of(context).pop(),

                        child: Text('OK'),

                      ),

                    ],

                  );

                },

              );

            },

            child: Text('Submit'),

          ),

        ),

      ],

    );

  }

}


7b)Implement form validation and error handling.

import 'package:flutter/material.dart';

void main() {

  runApp(MyApp());

}

class MyApp extends StatelessWidget {

  @override

  Widget build(BuildContext context) {

    return MaterialApp(

      title: 'User Form',

      home: Scaffold(

        appBar: AppBar(

          title: Text('User Input Form'),

        ),

        body: SingleChildScrollView(

          padding: EdgeInsets.all(16.0),

          child: UserForm(),

        ),

      ),

    );

  }

}

class UserForm extends StatefulWidget {

  @override

  State<UserForm> createState() => _UserFormState();

}

class _UserFormState extends State<UserForm> {

  final _formKey = GlobalKey<FormState>();


  String? _name;

  String? _email;

  String? _phoneNumber;

  String? _collegeName;


  @override

  Widget build(BuildContext context) {

    return Form(

      key: _formKey,

      child: Column(

        crossAxisAlignment: CrossAxisAlignment.start,

        children: [

          Text('Please fill in the form:', style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold)),

          SizedBox(height: 20),


          // Name Field

          TextFormField(

            decoration: InputDecoration(

              labelText: 'Name',

              border: OutlineInputBorder(),

              prefixIcon: Icon(Icons.person),

            ),

            validator: (value) {

              if (value == null || value.trim().isEmpty) {

                return 'Name is required';

              }

              return null;

            },

            onSaved: (value) => _name = value,

          ),

          SizedBox(height: 16),


          // Email Field

          TextFormField(

            decoration: InputDecoration(

              labelText: 'Email ID',

              border: OutlineInputBorder(),

              prefixIcon: Icon(Icons.email),

            ),

            keyboardType: TextInputType.emailAddress,

            validator: (value) {

              if (value == null || value.trim().isEmpty) {

                return 'Email ID is required';

              }

              if (!RegExp(r'^[^@]+@[^@]+\.[^@]+').hasMatch(value)) {

                return 'Enter a valid email ID';

              }

              return null;

            },

            onSaved: (value) => _email = value,

          ),

          SizedBox(height: 16),


          // Phone Number Field

          TextFormField(

            decoration: InputDecoration(

              labelText: 'Phone Number',

              border: OutlineInputBorder(),

              prefixIcon: Icon(Icons.phone),

            ),

            keyboardType: TextInputType.phone,

            validator: (value) {

              if (value == null || value.trim().isEmpty) {

                return 'Phone Number is required';

              }

              // Basic phone number validation (digits only, length 7-15)

              if (!RegExp(r'^\d{7,15}$').hasMatch(value)) {

                return 'Enter a valid phone number (7-15 digits)';

              }

              return null;

            },

            onSaved: (value) => _phoneNumber = value,

          ),

          SizedBox(height: 16),


          // College Name Field

          TextFormField(

            decoration: InputDecoration(

              labelText: 'College Name',

              border: OutlineInputBorder(),

              prefixIcon: Icon(Icons.school),

            ),

            validator: (value) {

              if (value == null || value.trim().isEmpty) {

                return 'College Name is required';

              }

              return null;

            },

            onSaved: (value) => _collegeName = value,

          ),

          SizedBox(height: 24),


          // Submit Button

          Center(

            child: ElevatedButton(

              onPressed: () {

                if (_formKey.currentState!.validate()) {

                  _formKey.currentState!.save();


                  showDialog(

                    context: context,

                    builder: (context) => AlertDialog(

                      title: Text('Form Submitted'),

                      content: Text(

                          'Name: $_name\nEmail ID: $_email\nPhone Number: $_phoneNumber\nCollege Name: $_collegeName'),

                      actions: [

                        TextButton(

                          onPressed: () => Navigator.pop(context),

                          child: Text('OK'),

                        )

                      ],

                    ),

                  );

                }

              },

              child: Text('Submit'),

            ),

          ),

        ],

      ),

    );

  }

}

final _formKey = GlobalKey<FormState>();

  • This line declares a final variable _formKey inside the _UserFormState class.
  • _formKey is a GlobalKey<FormState>.
  • The GlobalKey uniquely identifies the Form widget in the widget tree and allows access to its state.

Why is _formKey Inside the State Class?

The form key is part of the state because:

  • It is used to access and manage the Form's state (validation, saving, resetting).
  • The lifecycle of the form key is tied to the state of the widget, not the widget itself.

value.trim()
The .trim() method is called on the value string.
It returns a new string with all leading and trailing whitespace removed.
For example:
" hello " becomes "hello"
" " becomes "" (an empty string)
This is important because users might enter spaces without any actual text.

RegExp(r'^[^@]+@[^@]+\.[^@]+'):
r'': The r before the string indicates a raw string, which means that escape sequences are not processed. This is useful for regular expressions.
^: Asserts the start of the string.
[^@]+: Matches one or more characters that are not @. This represents the local part of the email.
@: Matches the @ symbol, which is a required part of an email address.
[^@]+: Again matches one or more characters that are not @, representing the domain name.
\.: Matches a literal dot (.), which separates the domain name from the top-level domain (TLD).
[^@]+: Matches one or more characters that are not @, representing the TLD (like .com, .org, etc.).
Overall, this regex checks for a basic structure of an email address.
hasMatch Method:

hasMatch(value): This method checks if the value string matches the regular expression pattern defined above. It returns true if there is a match and false otherwise.
Negation:

The ! operator negates the result of hasMatch. Therefore, if hasMatch returns false (meaning the email format is invalid), the code inside the if block will execute.

  • There is at least one character before the "@".
  • There is at least one character after the "@" and before the period.[This matches a literal period (".").]
  • There is at least one character after the period.

Comments

Popular posts from this blog

EXPERIMENT-3

EXPERIMENT-2

EXPERIMENT-4