Creating a Login Screen with flutter with validation - Here’s a step-by-step guide to creating a login screen in Flutter with validation, using the provided code:

1. Set Up Your Flutter Project

Make sure you have a Flutter project set up. If not, you can create a new Flutter project using:

flutter create my_login_app
cd my_login_app

In lib/main.dart, update the home property of your MaterialApp to use the LoginScreen:

import 'package:flutter/material.dart';
import 'login_screen.dart'; // Import the login screen file

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

class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: LoginScreen(), // Set LoginScreen as the home widget
);
}
}

2. Create the Login Screen

Replace the content of lib/main.dart with the provided code or create a new Dart file (e.g., login_screen.dart) and add the following code to it:

Here's the updated code with the confirm password functionality:

login_screen.dart

import 'package:flutter/material.dart';

class LoginScreen extends StatefulWidget {
  @override
  _LoginScreenState createState() => _LoginScreenState();
}

class _LoginScreenState extends State<LoginScreen> {
  final _formKey = GlobalKey<FormState>(); // Form key for validation
  final TextEditingController _firstNameController = TextEditingController();
  final TextEditingController _lastNameController = TextEditingController();
  final TextEditingController _passwordController = TextEditingController();
  final TextEditingController _confirmPasswordController = TextEditingController(); // New controller for confirm password

  bool _passwordVisible = false; // Password visibility toggle
  bool _confirmPasswordVisible = false; // Confirm password visibility toggle

  @override
  void initState() {
    super.initState();
    _passwordVisible = false;
    _confirmPasswordVisible = false;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Login Screen'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Form(
          key: _formKey,
          child: Column(
            children: <Widget>[
              TextFormField(
                controller: _firstNameController,
                decoration: InputDecoration(labelText: 'First Name'),
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return 'Please enter your first name';
                  }
                  return null;
                },
              ),
              TextFormField(
                controller: _lastNameController,
                decoration: InputDecoration(labelText: 'Last Name'),
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return 'Please enter your last name';
                  }
                  return null;
                },
              ),
              TextFormField(
                controller: _passwordController,
                decoration: InputDecoration(
                  labelText: 'Password',
                  suffixIcon: IconButton(
                    icon: Icon(
                      _passwordVisible ? Icons.visibility : Icons.visibility_off,
                    ),
                    onPressed: () {
                      setState(() {
                        _passwordVisible = !_passwordVisible;
                      });
                    },
                  ),
                ),
                obscureText: !_passwordVisible,
                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;
                },
              ),
              TextFormField(
                controller: _confirmPasswordController,
                decoration: InputDecoration(
                  labelText: 'Confirm Password',
                  suffixIcon: IconButton(
                    icon: Icon(
                      _confirmPasswordVisible ? Icons.visibility : Icons.visibility_off,
                    ),
                    onPressed: () {
                      setState(() {
                        _confirmPasswordVisible = !_confirmPasswordVisible;
                      });
                    },
                  ),
                ),
                obscureText: !_confirmPasswordVisible,
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return 'Please confirm your password';
                  } else if (value != _passwordController.text) {
                    return 'Passwords do not match';
                  }
                  return null;
                },
              ),
              SizedBox(height: 20),
              ElevatedButton(
                onPressed: () {
                  if (_formKey.currentState!.validate()) {
                    // If the form is valid, display a snackbar or handle submission
                    ScaffoldMessenger.of(context).showSnackBar(
                      SnackBar(content: Text('Processing Data')),
                    );
                  }
                },
                child: Text('Submit'),
              ),
            ],
          ),
        ),
      ),
    );
  }

  @override
  void dispose() {
    _firstNameController.dispose();
    _lastNameController.dispose();
    _passwordController.dispose();
    _confirmPasswordController.dispose();
    super.dispose();
  }
}

Output

3. Understanding the Code

Imports and Setup

  • import 'package:flutter/material.dart';: Imports Flutter's material design package.

State Management

  • final _formKey = GlobalKey<FormState>();: Creates a key to uniquely identify the form and manage validation.
  • TextEditingController: Controllers for managing text input and validation.

Password Visibility

  • bool _passwordVisible and _confirmPasswordVisible: Booleans to toggle password visibility.

UI Elements

  • TextFormField: Input fields for the first name, last name, password, and confirm password.
    • validator: Function to validate input and show error messages.
    • suffixIcon: An icon button to toggle the visibility of the password.

Form Submission

  • ElevatedButton: A button to submit the form. It validates the form and shows a snackbar if successful.

Resource Cleanup

  • dispose(): Dispose of controllers when they are no longer needed to free up resources.

4. Testing the Login Screen

  • Run the App: Execute flutter run to see the login screen in action.
  • Validation: Try submitting the form with empty fields and incorrect passwords to test the validation logic.

5. Additional Enhancements

  • Styling: Customize the appearance of input fields and buttons.
  • Error Handling: Implement more sophisticated error handling and feedback mechanisms.
  • Navigation: Add navigation to different screens based on successful login.

This setup provides a solid foundation for a login screen in Flutter with basic validation and UI features.m password, and visibility toggling for both password fields.

Related Articles