Flutterexperts

Empowering Vision with FlutterExperts' Expertise
Email Verification with Flutter Firebase

Hello!! Flutter Devs, In this article we will learn how to verify a user’s email address using an email verification link with the help of firebase authentication.

If you have used firebase authentication, you must have noticed that you can Sign in with any anonymous email address that is not yours. So you must be finding a way to verify that email address for the authenticity of that user’s email address.

If you’re looking for the best Flutter app development company for your mobile application then feel free to contact us at — support@flutterdevs.com.



Firebase Project Setup:

First, we will set up our Project with Firebase, skip this part if you have already done this.

Open the Firebase console and click the “Add project” option.

Enter your project name here!

Now by clicking continue you will be redirected to the next steps, where you can enable Google Analytics for your Firebase project.

Android Setup:

Click on Android Icon on the dashboard of the firebase project console.

Now Register your android app by filling in the required details.

Now Download the google-services.json file from here and put it in your android/app folder.

IOS Configuration:

Register the IOS app to Firebase, and the iOS bundle Id must be the same in the Xcode project and on the firebase console.

Download configuration files for your app and adds them to your project folder.

Implementation:

Enable Email/Password authentication on the firebase console

Add dependencies to pubspec — yaml file.

dependencies:firebase_core: ^2.1.1
firebase_auth: ^4.1.0

We will now initialize Firebase in our project

Let’s create a new file called firebase_constants.dart, where we are going to make a global auth instance for our app and initialize that in main. dart file.

firebase_constants.dart

import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_core/firebase_core.dart';
final Future<FirebaseApp> firebaseInitialization = Firebase.initializeApp();
FirebaseAuth auth = FirebaseAuth.instance;

main.dart

void main()async {
WidgetsFlutterBinding.ensureInitialized();
await firebaseInitialization;
runApp(const MyApp());
}

Let’s create a function for the Sign-Up button to handle email authentication. This function will register a user in firebase.

static Future<User?> signUp(
{required String userEmail,
required String password,
required BuildContext context}) async {
try {
UserCredential userCredential = await FirebaseAuth.instance
.createUserWithEmailAndPassword(email: userEmail, password: password);
return userCredential.user;
} on FirebaseAuthException catch (e) {
if (e.code == 'weak-password') {
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text('The password provided is too weak.')));
} else if (e.code == 'email-already-in-use') {
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text('The account already exists for that email.')));
}
return null;
} catch (e) {
debugPrint(e.toString());
return null;
}
}

auth_page.dart

import 'package:email_auth/utils/constants/firebase_constants.dart';
import 'package:email_auth/views/auth/email_verification_page.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';

class AuthPage extends StatefulWidget {
const AuthPage({Key? key}) : super(key: key);

@override
State<AuthPage> createState() => _AuthPageState();
}

class _AuthPageState extends State<AuthPage> {

final TextEditingController _emailController = TextEditingController();
final TextEditingController _passwordController = TextEditingController();
bool _isLoading = false;

static Future<User?> signUp(
{required String userEmail,
required String password,
required BuildContext context}) async {
try {
UserCredential userCredential = await FirebaseAuth.instance
.createUserWithEmailAndPassword(email: userEmail, password: password);
return userCredential.user;
} on FirebaseAuthException catch (e) {
if (e.code == 'weak-password') {
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text('The password provided is too weak.')));
} else if (e.code == 'email-already-in-use') {
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text('The account already exists for that email.')));
}
return null;
} catch (e) {
debugPrint(e.toString());
return null;
}
}

@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 18),
child: Column(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.center,
children: [
TextFormField(
controller: _emailController,
// validator: (val) => widget.onValidate(val),
decoration: InputDecoration(
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(12),
borderSide:
const BorderSide(color: Colors.grey, width: 1),
),
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(12),
borderSide:
const BorderSide(color: Colors.grey, width: 1),
),
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(12),
borderSide:
const BorderSide(color: Colors.grey, width: 1),
),
filled: true,
fillColor: Colors.white,
hintText: 'Enter Email',
// hintStyle: AppTextStyle.lightGreyText,
isDense: true,
contentPadding:
const EdgeInsets.symmetric(horizontal: 12, vertical: 15),
),
),
const SizedBox(height: 20,),
TextFormField(
controller: _passwordController,
decoration: InputDecoration(
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(12),
borderSide:
const BorderSide(color: Colors.grey, width: 1),
),
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(12),
borderSide:
const BorderSide(color: Colors.grey, width: 1),
),
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(12),
borderSide:
const BorderSide(color: Colors.grey, width: 1),
),
filled: true,
fillColor: Colors.white,
hintText: 'Enter Password',
// hintStyle: AppTextStyle.lightGreyText,
isDense: true,
contentPadding:
const EdgeInsets.symmetric(horizontal: 12, vertical: 15),
),
obscureText: true,
),
const SizedBox(height: 20,),
_isLoading ? const CircularProgressIndicator() : ElevatedButton(onPressed: ()async{
setState(() {
_isLoading = true;
});
await signUp(userEmail: _emailController.text, password: _passwordController.text, context: context);
if(auth.currentUser != null){
Navigator.push(context, MaterialPageRoute(builder: (ctx)=>const EmailVerificationScreen()));
}
setState(() {
_isLoading = false;
});
}, child: const Text('Sign Up'))
],
),
),
),
);
}
}

When we run the application, we ought to get the screen’s output like the underneath screen capture.

Output

Also, let’s create a page where we will check the status of email verification.

Here we will set a periodic timer in the initState() state that will check the status of the email if it is verified or not.

email_verification_page.dart

import 'dart:async';
import 'package:email_auth/utils/constants/firebase_constants.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
class EmailVerificationScreen extends StatefulWidget {
const EmailVerificationScreen({Key? key}) : super(key: key);

@override
State<EmailVerificationScreen> createState() =>
_EmailVerificationScreenState();
}

class _EmailVerificationScreenState extends State<EmailVerificationScreen> {
bool isEmailVerified = false;
Timer? timer;
@override
void initState() {
// TODO: implement initState
super.initState();
FirebaseAuth.instance.currentUser?.sendEmailVerification();
timer =
Timer.periodic(const Duration(seconds: 3), (_) => checkEmailVerified());
}

checkEmailVerified() async {
await FirebaseAuth.instance.currentUser?.reload();

setState(() {
isEmailVerified = FirebaseAuth.instance.currentUser!.emailVerified;
});

if (isEmailVerified) {
// TODO: implement your code after email verification
ScaffoldMessenger.of(context)
.showSnackBar(SnackBar(content: Text("Email Successfully Verified")));

timer?.cancel();
}
}

@override
void dispose() {
// TODO: implement dispose
timer?.cancel();
super.dispose();
}

@override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
body: SingleChildScrollView(
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
const SizedBox(height: 35),
const SizedBox(height: 30),
const Center(
child: Text(
'Check your \n Email',
textAlign: TextAlign.center,
),
),
const SizedBox(height: 8),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 32.0),
child: Center(
child: Text(
'We have sent you a Email on ${auth.currentUser?.email}',
textAlign: TextAlign.center,
),
),
),
const SizedBox(height: 16),
const Center(child: CircularProgressIndicator()),
const SizedBox(height: 8),
const Padding(
padding: EdgeInsets
.symmetric(horizontal: 32.0),
child: Center(
child: Text(
'Verifying email....',
textAlign: TextAlign.center,
),
),
),
const SizedBox(height: 57),
Padding(
padding: const EdgeInsets
.symmetric(horizontal: 32.0),
child: ElevatedButton(
child: const Text('Resend'),
onPressed: () {
try {
FirebaseAuth.instance.currentUser
?.sendEmailVerification();
} catch (e) {
debugPrint('$e');
}
},
),
),
],
),
),
),
);
}
}

When we run the application, we ought to get the screen’s output like the underneath screen capture.

Output

Now if your email address is correct then you are going to receive an email from your firebase project and now by clicking on the link you can verify your email address.

Yay!! Your email is now verified successfully.

Email Verified Screen

When we run the application, we ought to get the screen’s output like the underneath screen video.

Final Output Video

Conclusion:

In this article, we learned how easily we can do email verification with the help of Firebase.

❤ ❤ Thanks for reading this article ❤❤

If I got something wrong? Let me know in the comments. I would love to improve.

Clap 👏 If this article helps you.


GitHub Link:

find the source code of the Email Verification using Firebase:

GitHub – flutter-devs/email_verification_using_firebase
A new Flutter project. This project is a starting point for a Flutter application. A few resources to get you started…github.com


FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. Hire a flutter developer for your cross-platform Flutter mobile app project on an hourly or full-time basis as per your requirement! For any flutter-related queries, you can connect with us on Facebook, GitHub, Twitter, and LinkedIn.

We welcome feedback and hope you share what you’re working on using #FlutterDevs. We truly enjoy seeing how you use Flutter to build beautiful, interactive web experiences.


Leave comment

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