Introduction

Rarely have we seen that mobile applications are connected to the backend. There are other platforms- AWS or Azure, but no platform could stand Firebase. With the help of Firebase and Flutter, one can develop mobile applications in a better way.

In this tutorial, we will learn about building a demo application from scratch and implementing Email Authentication using Firebase Auth + Flutter.

Tutorial Goal: Email and Password Authentication using Firebase Auth + Flutter

What are we building?

The step-by-step guide will help to us build a basic application where we can sign up and login with email and password using flutter + firebase authentication. Watch the below video to get the idea of our demo app.

What is Firebase Authentication?

Most of the applications require authentication to verify the user’s identity. Firebase Authentication allows you to use its back-end services by providing SDKs and convenient UI libraries for user authentication in your app. It makes the process less complicated and easy to develop. One can authenticate the user with the help of passwords, phone numbers, or identity providers ( Facebook, Google, and Twitter).

What does Firebase Authentication provide?

  • Email/password authentication
  • Sign in with Google, Apple, Facebook, Twitter, Github
  • Phone number authentication
  • Custom authentication
  • Anonymous authentication

From the list mentioned above, I’ll be covering sign up and sign in with email and password Firebase auth + Flutter. So without further ado, let’s get started with some technical work.

Steps to Implement Email and Password Authentication using Flutter Firebase Auth

Follow the steps to Firebase email and password authentication in the Flutter application.

1. Create Flutter project

Run the below command to create a flutter project. You can name it anything.

Copy Text
flutter_firebase_auth
flutter create flutter_firebase_auth

2. Add dependencies

Update your pubspec.yaml file to add dependencies.

Copy Text
dependencies:
 flutter_test:
   sdk: flutter
 cupertino_icons: ^1.0.2
 firebase_auth: ^1.0.1 # add this line
 firebase_core: ^1.0.2 # add this line

Run the following command to install the packages.

Copy Text
flutter pub get

Your pubspec.yaml file would look something like this-

Add dependencies

For using these packages, we need to import them as mentioned below.

Copy Text
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_core/firebase_core.dart';

Further moving towards the initial Firebase Setup.

3. Create Firebase Project

We need to create a Firebase project; for that follow the instructions.

  • Visit the Firebase Console.
  • Start by adding a New Project
  • Giving the project a name and agreeing to all they’ve asked
  • Click ‘Create Project.’

Once you’re done creating the project, it’s time to integrate it with Android and iOS applications.

Stop wasting time and start taking actions!
Want to build a high-performance Flutter app? Get in touch with our Flutter community to develop your dream project. We are here to serve your purpose. Contact us and hire Flutter developer now!

4. Configure Firebase with Android and iOS Application

For configuring the applications, first click on +Add app and later on iOS.

Click on Add App Click on iOS

➡ Configure iOS App

Register iOS application

For registering the iOS app, you have to provide unique iOS bundle ID – your iOS app bundle identifier. You can find it in the general setting of Xcode, by default it will take com.example.application_name. The next field App nickname is optional.

Add Firebase to iOS app

Download iOS Config file

After filling the required fields, you’ll see something like this. Further click on Download GoogleServices-Info.plist and place it in MyApplication folder as shown below.

For Linux/Windows, place this file in ios/Runner/Directory.

Download config file

Skip steps (3) and (4) as we are using packages. Hit ‘Continue to console’ for completing the process.

Add firebase to your iOS app

➡ Configure Android App

Register Android application

For registering the android app, you have to provide a unique package name. For that, you can find it at android>app>build.gradle, by default it will take com.example.application_name. The next field App nickname is optional.

Register your Android application

Download Android Config file

After filling the required fields, you’ll see something like this. Download google-services.json and place it in MyApplication/app folder.

Register your Android application

You can skip the next step as we are using: Firebase core and Firebase auth packages. Click ‘Continue to Console’ to complete the process.

Register your Android application

5. Enable Email/Password Authentication in Firebase

On visiting the Firebase dashboard, click ‘Authentication.’

Enable Firebase Email Authentication

Under the Sign-in method click ‘Email/Password’ and enable it using the toggle button. Use the below screenshots for your reference.

Firebase Email Authentication Sign-in method setting and integrating Firebase Authentication

So, we are done setting and integrating your Flutter app with Firebase email/password authentication.

6. Initialize Firebase App

Open main.dart and use the following code snippet to initialize Firebase App.

// main.dart

Copy Text
future main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  runApp(MyApp());
}

7. Create Helper Class for Authentication

Create a file, name it according to your choice; here authentication.dart and use the following code for creating helper class for authentication.

// authentication.dart

Copy Text
import 'package:firebase_auth/firebase_auth.dart';

class AuthenticationHelper {
  final FirebaseAuth _auth = FirebaseAuth.instance;
  get user => _auth.currentUser;

 //SIGN UP METHOD
  Future signUp({String email, String password}) async {
    try {
      await _auth.createUserWithEmailAndPassword(
        email: email,
        password: password,
      );
      return null;
    } on FirebaseAuthException catch (e) {
      return e.message;
    }
  }

  //SIGN IN METHOD
  Future signIn({String email, String password}) async {
    try {
      await _auth.signInWithEmailAndPassword(email: email, password: password);
      return null;
    } on FirebaseAuthException catch (e) {
      return e.message;
    }
  }

  //SIGN OUT METHOD
  Future signOut() async {
    await _auth.signOut();

    print('signout');
  }
}

We will call the AuthenticationHelper from SignUp and Login components on clicking the signup and login button, respectively. These two functions will take two parameters and then further pass it for Firebase Authentication.

8. Create components for Login and Sign Up

Create two components for login and signup – Login.dart and Signup.dart, respectively.

Call AuthenticationHelper, which we created in the above step.

Use the following code snippet to perform on clicking the Sign Up button.

// Signup.dart

Copy Text
// Get username and password from the user.Pass the data to 
// helper method

AuthenticationHelper()
   .signUp(email: email, password: password)
   .then((result) {
    	if (result == null) {
        Navigator.pushReplacement(context,
           MaterialPageRoute(builder: (context) => Home()));
       } else {
          Scaffold.of(context).showSnackBar(SnackBar(
          content: Text(
              result,
              style: TextStyle(fontSize: 16),
             ),
          ));
       }
  });

Use the following code snippet to perform on clicking the Login button.

// Login.dart

Copy Text
AuthenticationHelper()
   .signIn(email: email, password: password)
      .then((result) {
         if (result == null) {
           Navigator.pushReplacement(context,
             MaterialPageRoute(builder: (context) => Home()));
          } else {
             Scaffold.of(context).showSnackBar(SnackBar(
                 content: Text(
                 result,
                style: TextStyle(fontSize: 16),
                   ),
              ));
           }
      });

The function takes two arguments: email and password. On successfully executing the function and returning no errors, i.e., result == null, the app will be redirected to the Home page.

Github Repository: Flutter Firebase Auth Example

Feel free to visit the github repository: firebase-auth-flutter-example and clone the demo to play around with the code.

Conclusion

So this was all about implementing email/password authentication using Firebase Auth + Flutter. I hope your purpose of landing on this tutorial has served you well. Flutter is a popular framework for developing mobile applications at our ease. The combination of Flutter and Firebase makes the development process more straightforward than before. Are you a Flutter enthusiast? Yes! Then Flutter tutorials page is for you! Learn and explore more about Flutter and start building your applications. We are a leading Flutter App development Company and have skillful and dedicated developers having expertise with Flutter as well as Firebase. In case you require a helping hand in developing your project, then contact us and hire Flutter app developer.

Flutter Tutorials

Get Advanced Knowledge

EXPLORE NOW

Get In Touch

[email protected]

Your Success Is Guaranteed !

We accelerate the release of digital product and guaranteed their success

We Use Slack, Jira & GitHub for Accurate Deployment and Effective Communication.