Firebase Authentication Services in Flutter

Anmol Gupta
6 min readApr 10, 2022

--

Introduction

In this blog, we shall learn about how we can connect our flutter app with firebase and implement authentication using firebase, we shall also learn how we can handle the errors on failure events.

Connect the flutter app with firebase:

  • The first step is to create a firebase project
  • Creating your firebase project you will land up on this screen, and click on the android icon.
Figure:1 Firebase dashboard

After clicking on the android icon, you will land upon the below screen:

  • Enter your package name, which you can find in your app-level build.gradle file inside defaultConfig in applicationId , paste it and click on the Register App button.
Figure:2 Add package name and click on register app
  • Download the google-services.json file and add this file inside the app src folder.
Figure: 3Download google-services.json file
Figure:3 Add google-services.json file in your app folder
  • Add the following dependency in your <project>/build.gradle file
buildscript {
repositories {
// Check that you have the following line (if not, add it):
google() // Google's Maven repository
}
dependencies {
...
// Add this line
classpath 'com.google.gms:google-services:4.3.10'
}
}
allprojects {
...
repositories {
// Check that you have the following line (if not, add it):
google() // Google's Maven repository
...
}
}
  • Add the following line in your <project>/<app-module>/build.gradle file.
apply plugin: 'com.android.application'// Add this line
apply plugin: 'com.google.gms.google-services'
dependencies {
// Import the Firebase BoM
implementation platform('com.google.firebase:firebase-bom:29.0.1')
// Add the dependency for the Firebase SDK for Google Analytics
// When using the BoM, don't specify versions in Firebase dependencies
implementation 'com.google.firebase:firebase-analytics'
// Add the dependencies for any other desired Firebase products
// https://firebase.google.com/docs/android/setup#available-libraries
}
  • Firebase configuration in the flutter app is done, now we will initialize firebase inside our app. To initialize the firebase we need firebase_core package, it provides initializeApp() method to initialize firebase in the flutter app.
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(MyHomePage());
}
  • Go to the Authentication section and click on get started.
Figure:13
  • Click on the Sign-in method and choose the Email/password option.
Figure:14
  • Enable the Email/Password option and save.
Figure:15

Now we have enabled the firebase email password sign-in authentication and now we will implement it in our flutter app.

Installing firebase_auth package:

Add firebase_auth package inside your pubspec.yaml

firebase_auth: ^1.1.0

This package provides us with various methods for signup, sign-in, changing passwords, etc.

Now we will look at who can perform authentication using this package:

  • Sign-up Method

To sign up with an email and password firebase_auth package provides us createUserWithEmailAndPassword methods that take two parameters email, and password .

Future createUser({String email, String password}) async {
await FirebaseAuth.instance
.createUserWithEmailAndPassword(email: email, password: password);
}
  • Sign-in Method

For sign in firebase_auth package provides us signInWithEmailAndPassword the method that also takes emailand passwordas parameters.

Future signIn({String email, String password}) async {
await FirebaseAuth.instance
.signInWithEmailAndPassword(email: email, password: password);
}
  • Sign-up Error And Success handling

To handle errors of sign up and sign in we will use onErrormethod of the Future. When we initialize the create user method we will use the then method for success code execution and onError method for error handling. To display the error message we will use snackBar .

createUser(email: email, password: password)
.then((value) {
//navigate to new screen
})
.onError(
(error, stackTrace) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(
error.code.toString(),
),
),
);
},
);

sign-in error and success handling:

signIn(email: email, password: password)
.then((value) {
//navigate to new screen
})
.onError(
(error, stackTrace) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(
error.code.toString(),
),
),
);
},
);
  • Delete User

To delete the user we first need to re-authenticate the user and to re-authenticate the user we need the current user credentials.

FirebaseAuth provides us currentUser , using this user object we can re-authenticate the user using reauthenticateWithCredential method, this method takes AuthCredentialas an input.

User user = FirebaseAuth.instance.currentUser;

Using EmailAuthProvider class we can get the AuthCredential .

AuthCredential credentials =
EmailAuthProvider.credential(email: email, password: password);

Now we will re-authenticate the user and delete the user.

UserCredential result =
await user.reauthenticateWithCredential(credentials);
await result.user.delete();

Method:

Future deleteUser(String email, String password) async {
User user = FirebaseAuth.instance.currentUser;
AuthCredential credentials =
EmailAuthProvider.credential(email: email, password: password);
UserCredential result =
await user.reauthenticateWithCredential(credentials);
await result.user.delete();
}

Error and Success Handling:

deleteUser(user.email, passwordController.text)
.then((value) {
//navigate to auth screen
}).onError((error, stackTrace) {
Navigator.of(context).pop();
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(error.toString()),
),
);
});
  • Change Password

To change the password firebase_auth package provides us sendPasswordResetEmail method that sends the email on the user's email and from there we can change the password.

Future changePassword({String email}) async {
await FirebaseAuth.instance.sendPasswordResetEmail(email: email);
}

Error and Success Handling:

changePassword(email: user.email)
.then((value) => ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(
"Password reset link sent to email: ${user.email}"),
),
))
.onError(
(error, stackTrace) =>
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(error.code.toString()),
),
),
);
  • SignOut
Future logOut() async {
await FirebaseAuth.instance.signOut();
}

Error and Success Handling:

logOut()
.then(
(value) => Navigator.of(context)
.popUntil((route) => route.isFirst),
)
.onError(
(error, stackTrace) =>
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(
error.code.toString(),
),
),
),
);

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.

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

Become a Flutter Developer and Unleash Your Creativity!

Ready to take your mobile app development skills to the next level? Our comprehensive Flutter course is perfect for beginners, guiding you through the process of building stunning native applications for iOS, Android, and the web.

With Flutter’s streamlined approach and the Dart programming language, you’ll learn how to create visually appealing apps with just one codebase. No need to master multiple languages — Flutter simplifies the process, making it easier and faster to bring your app ideas to life.

From setting up your development environment to mastering key concepts like widgets, navigation, forms, and state management, you’ll gain practical knowledge every step of the way. Plus, you’ll even explore exciting AI-powered chatbot development using OpenAI APIs.

Enroll today and discover the world of Flutter development. Unleash your creativity and build beautiful, high-performance native mobile applications with ease.

https://www.udemy.com/course/flutter-bootcamp-build-native-mobile-apps-with-dart-2023/

--

--