User Authentication with Firebase for Flutter Apps

User authentication is the verification process of a user to ensure they are who they are. User authentication is essential in protecting user accounts by requiring users to identify themselves. It also provides a personalized experience for users, such as customers and sellers, on an e-commerce app.

It has been a debate in the tech community on mobile applications being the same as frontend web apps because they deal primarily with the client side. Therefore, a backend functionality is needed to ensure the app can store user data and provide services like authentication. Firebase provides backend services for applications such as a database and authentication. We shall configure Firebase Auth Service to a Flutter app.

The first step is connecting Firebase SDK to your app by installing and initializing it. You can follow the docs here.

How to Add Firebase Authentication to your App

Run the following command to install the plugin

flutter pub add firebase_auth

Run your app to rebuild it.

flutter run

Import the code to activate the plugin in your code.

import 'package:firebase_auth/firebase_auth.dart';

Go to your console on Firebase Console and select the authentication sign-in method and the identity providers you require for your project.

authentication firebase.png

We shall use the email/password authentication method for this first tutorial in this Firebase series.

How to Create the User Sign-Up Screen

We shall work on several screens in this series, but for today, we shall learn how to create the signup screen and add the Firebase Authentication for email/password.

The first step will be separating our concerns i.e, creating different folders for different functionalities. We shall have screens and utils(utilities) in our lib folder.In the utils folder, we shall have an auth file where we shall have the Firebase Authentication functionality.

How to Create Firebase Authentication functionality

First, create an authentication file in the utils folder. Then import code to activate the plugin in this file.

import 'package:firebase_auth/firebase_auth.dart';

Then import the code to the screen in which the authentication will serve.

import '../screens/signup.dart';

Next, create a class and initialize Firebase here with the following lines.

class Authentication {
  static Future<FirebaseApp> initializeFirebase() async {
    FirebaseApp firebaseApp = await Firebase.initializeApp();
    return firebaseApp;
  }
}

Then have the following lines to enable the password and email signup functionality.

  static void signup(BuildContext context, String email, String password) {
    FirebaseAuth auth = FirebaseAuth.instance;
    auth.createUserWithEmailAndPassword(email: email, password: password).then(
        (_) => Navigator.of(context).pushReplacement(
            MaterialPageRoute(builder: (context) => const Home())));
  }

Here we pass the email and password taken from the text field in the Sign Up page into the createUserWithEmailAndPassword method. Then the navigator will send the user to another page, preferably the home page, after signing up.

How to Create the Sign-up Page

Create global variables _email and _password so they can be accessed by multiple widgets in the signup screen file.

This function is used with the email text form field to take in the value input by the user and store it in a variable, in this case, _email.

onChanged: (value) {
                setState(() {
                  _email = value.trim();
                });
              },

The same applies to this in the password text form field. They will then be sent to the auth file in utils after the onPressed is fired when the user presses sign-up.

onChanged: (value) {
                setState(() {
                  _password = value.trim();
                });
              },

This function is used with buttons to manage actions that are to be fired once the button is pressed. The function will send the email and password to the authentication class in the auth file in utils for this button. This will then complete the action of signing up the user.

onPressed: () {
                    Authentication.signup(context, _email, _password);
                  },

This is the code for the Sign-Up screen.

// ignore_for_file: prefer_const_constructors

import 'package:flutter/material.dart';
import '../utils/auth.dart';

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

  @override
  State<SignUp> createState() => _SignUpState();
}

class _SignUpState extends State<SignUp> {
  late String _email, _password;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        elevation: 5,
        title: const Text('Sign Up Screen'),
        centerTitle: true,
      ),
      body: Padding(
        padding: const EdgeInsets.only(top: 30.0, left: 10.0, right: 10),
        child: Column(
          children: [
            Center(
              child: Text(
                'Sign Up',
                style: TextStyle(fontSize: 30, fontWeight: FontWeight.bold),
              ),
            ),
            SizedBox(height: 20),
            TextField(
              onChanged: (value) {
                setState(() {
                  _email = value.trim();
                });
              },
              decoration: InputDecoration(
                  hintText: 'example@gmail.com',
                  border: OutlineInputBorder(
                      borderRadius: BorderRadius.all(Radius.circular(30.0)))),
            ),
            SizedBox(height: 20),
            TextField(
              onChanged: (value) {
                setState(() {
                  _password = value.trim();
                });
              },
              decoration: InputDecoration(
                  hintText: 'Enter your password',
                  border: OutlineInputBorder(
                      borderRadius: BorderRadius.all(Radius.circular(30.0)))),
            ),
            SizedBox(
              height: 30,
            ),
            Container(
              padding:  EdgeInsets.only(bottom: 0),
              width: MediaQuery.of(context).size.width,
              height: 50,
              child: ElevatedButton(
                  onPressed: () {
                    Authentication.signup(context, _email, _password);
                  },
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    // ignore: prefer_const_literals_to_create_immutables
                    children: [
                      Text(
                        'Sign up with email',
                        style: TextStyle(
                          fontWeight: FontWeight.bold,
                          fontSize:18,
                          color: Colors.white
                        ),
                      ),
                    ],
                    )
                    ),
            ),
            SizedBox(height: 10,),
          ],
        ),
      ),
    );
  }
}

The sample project we will work with is on this Github repo.

Follow along next time and we shall explore other functionality like the sign-out and learn more about Firebase. Thank you for reading and until next time, may the code be with you.