Pular para o conteúdo principal

Flutter Login Validation

Login validation is essential in any application that requires user authentication. Flutter provides various widgets for creating user interfaces, including the Login Validation widget. In this article, we will discuss how to use the Login Validation widget in Flutter.

Introduction

The Login Validation widget is used to validate user input when logging in. It ensures that the user enters the correct credentials before granting access to the application. The widget can be customized to suit your application's needs, such as changing the validation rules or adding custom error messages.

Steps to Create a Login Validation Widget

  1. Create a new Flutter application or open an existing one.
  2. Add the flutter_bloc dependency to your pubspec.yaml file.
  3. Create a new Bloc class that will handle the login validation logic.
  4. Create a new State class that will hold the current state of the login form.
  5. Create a new StatefulWidget that will display the login form.
  6. Add the necessary UI widgets to the login form, such as text fields and buttons.
  7. Implement the login validation logic in the Bloc class.
  8. Connect the login form to the Bloc class using the BlocBuilder widget.
  9. Display error messages if the user enters invalid credentials.

Here is an example of how to implement a Login Validation widget in Flutter:

import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

// Step 3
class LoginBloc extends Bloc<LoginEvent, LoginState> {
LoginBloc() : super(LoginState());


Stream<LoginState> mapEventToState(LoginEvent event) async* {
if (event is LoginButtonPressed) {
yield state.copyWith(isLoading: true);
try {
// Login validation logic goes here
// Check if user credentials are valid
bool isLoggedIn = await AuthService.login(event.username, event.password);
if (isLoggedIn) {
yield state.copyWith(isLoading: false, isSuccess: true);
} else {
yield state.copyWith(isLoading: false, error: 'Invalid credentials');
}
} catch (error) {
yield state.copyWith(isLoading: false, error: error.toString());
}
}
}
}

// Step 4
class LoginState {
final bool isLoading;
final bool isSuccess;
final String error;

LoginState({this.isLoading = false, this.isSuccess = false, this.error});

LoginState copyWith({bool isLoading, bool isSuccess, String error}) {
return LoginState(
isLoading: isLoading ?? this.isLoading,
isSuccess: isSuccess ?? this.isSuccess,
error: error ?? this.error,
);
}
}

// Step 5
class LoginScreen extends StatefulWidget {

_LoginScreenState createState() => _LoginScreenState();
}

class _LoginScreenState extends State<LoginScreen> {
final _usernameController = TextEditingController();
final _passwordController = TextEditingController();


Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Login'),
),
body: BlocProvider(
create: (context) => LoginBloc(),
child: BlocBuilder<LoginBloc, LoginState>(
builder: (context, state) {
return Padding(
padding: EdgeInsets.all(20),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
// Step 6
TextField(
controller: _usernameController,
decoration: InputDecoration(
hintText: 'Username',
),
),
SizedBox(height: 20),
TextField(
controller: _passwordController,
obscureText: true,
decoration: InputDecoration(
hintText: 'Password',
),
),
SizedBox(height: 20),
// Step 7
ElevatedButton(
onPressed: state.isLoading
? null
: () {
context.read<LoginBloc>().add(LoginButtonPressed(
username: _usernameController.text,
password: _passwordController.text));
},
child: state.isLoading
? CircularProgressIndicator()
: Text('Login'),
),
// Step 9
state.error != null
? Text(
state.error,
style: TextStyle(color: Colors.red),
)
: Container(),
],
),
);
},
),
),
);
}
}

// Step 1
void main() {
runApp(MaterialApp(
home: LoginScreen(),
));
}

// Step 2
class LoginEvent {}

class LoginButtonPressed extends LoginEvent {
final String username;
final String password;

LoginButtonPressed({ this.username, this.password});
}

More Examples

How to perform client-side login form authentication using flutter with LoginValidator library.

Many apps require user authentication. Most of these apps have a way to communicate to some remote webservice which performs the authentication on the server. However the client also has to perform some basic client-side authentication, mostly to validate the data input.

Because of that we need a way to validate textfields like username, email and password. Well we have a library that is easy yet flexible enough to cater for this type of validation.

In this piece we see how to perform login validation using the login-validator library.

Let's start.

What is Email Validator

A simple (but correct) Dart class for validating email addresses.

Installation

Dart requires the latest version of Dart. You can download the latest and greatest here.

  1. Depend on it
    Add this to your package's pubspec.yaml file:
dependencies:  
email_validator: '^1.0.0'
  1. Install it
    You can install packages from the command line:
$ pub get  

Alternatively, your editor might support pub. Check the docs for your editor to learn more.

  1. Import it
    Now in your Dart code, you can use:
import 'package:email_validator/email_validator.dart';
Usage
Read the unit tests under test, or see code example below:
void main() {
var email = "fredrik@gmail.com";
assert(EmailValidator.validate(email) == true);
}

Here are the files we explore:

  1. pubspec.yaml
  2. lib/main.dart

(a). pubspec.yaml

This is where we add our dependencies. Clearly you can see one of the dependencies is the email_validator, our third party library that abstracts us away the login validation logic.

name: login_validator
description: A new Flutter project.
dependencies:
flutter:
sdk: flutter
# The following adds the Cupertino Icons font to your application.
# Use with the CupertinoIcons class for iOS style icons.
cupertino_icons: ^0.1.2
email_validator: "0.1.4"
dev_dependencies:
flutter_test:
sdk: flutter
flutter:
uses-material-design: true

(b). login.dart

Our login.dart file.

import 'package:flutter/material.dart';
import 'package:email_validator/email_validator.dart';
//we create a widget <code>LoginPage

(c). main.dart

Here's the main.dart file. This is our main class as it contains our main method. As usual we start by importing our packages, derive from StatelessWidget, then write our main function.

import 'package:flutter/material.dart';
import 'package:login_validator/login.dart';
//Our app
class MyApp extends StatelessWidget {

Widget build(BuildContext context) {
return MaterialApp(
title: 'Mr Login',
theme: ThemeData(
primarySwatch: Colors.orange,
),
home: LoginPage(),
);
}
}
//main function
void main() => runApp(MyApp());

Conclusion

The Login Validation widget in Flutter is a powerful tool for ensuring that users enter valid credentials when logging in to an application. By following the steps outlined in this article, you can easily create a custom login form and validate user input using the flutter_bloc package. With this knowledge, you can create secure and user-friendly login screens for your Flutter applications.