Flutter Registration & login using Firebase.

Harsh Lohia
Code for Cause
Published in
11 min readJan 16, 2021
Flutter+Firebase ❤

In this article, we will learn how we can use Firebase Authentication in our Flutter App so that the user can sign-up and thereafter login to use our app.

What is firebase?

Firebase is a platform developed by Google for creating mobile and web applications.

What will we be making?

  1. Firstly, we will have a simple home page which has two buttons giving the users the option to either sign up, if they are using our app for the first time or sign in if he has visited our app before.
  2. On our sign-up page, we can ask for his required credentials like email-id and password. We can also ask for name, phone number, and also other credentials but for the sole purpose of learning how to use firebase authentication in our flutter app, email-id and password should be enough.
  3. On our login page, we will ask for his email id and password to direct him to our home page.
  4. Both the login page and sign-up page will validate the user credentials using the firebase authentication and direct them to our home page.
  5. We will have a simple home page to welcome the user right after the procedure of sign-up/login is complete.

First things first open up your Android Studio and Create a new Flutter project, and give it any name you want. Make sure you have 4 dart files in your lib folder.

  1. main.dart (default, will be there)
  2. welcome_screen.dart (To give the user the option for sign up or log in)
  3. login_screen.dart
  4. signup_screen.dart
  5. home_screen.dart

Now first to authenticate our app with firebase authentication we need to go to our google firebase console and start a new project. Follow this link to go to your fire up your firebase console https://firebase.google.com/

After opening your firebase console click on add/start a new project.

Project Screen

You can give your project any name you wish and hit continue.

Enable the google analytics for this project and hit continue.

Select Default Account for Firebase and Create Project.

It might 10–15 seconds and then you will be all set to use Firebase for authentication of your flutter app.

There was no such fuss about doing all that was it?

In this article we will learn how to set up our firebase project for android.

Click on the litter android button on this screen of your firebase project and you will be directed to a page to set up your application for android.

We need to give an android package name to our android app, now be careful about this it can’t be any name as it suggests your android package name is in your Flutter Project at the app-level `build.gradle`, file, you need to head over there and locate for the `applicationId`, tag in your `build.gradle`, file, that will be the name you need to put in your Android Package name.

After completing this step you click on Register App.

After registering your app you need to download the google-services.json file. Now after downloading this file make sure you drag or place this file in the android/app folder of your flutter project.

Now there is few other things we need to do before we are done with the settings of our android app.

Open up your project level `build.gradle`, file and add then copy the dependencies to your `build.gradle`, file.

Then we need to open our app level `build.gradle`, file and copy and add the dependencies to our app level `build.gradle`, file.

We are going to copy this line-

implementation `com.google.firebase:firebase-analytics`, and add this to our dependency.

We are also going to copy this line — apply plugin: `com.google.gms.google-services`, which implements our google services json file and paste it right at the end of our app/build.gradle file.

Also while you are in your app/build.gradle file I would suggest you to make few additions at some places to avoid any error you might encounter in the future while running your app.

First, we will make changes in our default config tag as follows:

defaultConfig {
// TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
applicationId "iamharsh.login_signup"
minSdkVersion 16
targetSdkVersion 29
versionCode flutterVersionCode.toInteger()
versionName flutterVersionName
multiDexEnabled true //add this line
}

Secondly, we will make changes in the dependencies tag as follows:

dependencies {
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
implementation 'com.google.firebase:firebase-analytics'
implementation 'com.android.support:multidex:1.0.3' //add this line
}

Now you are all set up to use firebase authentication in your project.

We will need two modules to use firebase in your flutter project for authentication

  1. firebase_core- A Flutter plugin to use the Firebase Core API, which enables connecting to multiple Firebase apps.
  2. firebase_auth- A Flutter plugin to use the Firebase Authentication API.

Now we will need to update our pubsec.yaml file and update the dependencies to use these modules.

dependencies:
flutter:
sdk: flutter



cupertino_icons: ^1.0.0
firebase_core: ^0.5.3
firebase_auth: ^0.18.4+1
modal_progress_hud: ^0.1.3

This is how your dependencies should look like in your pubspec.yaml file. After updating the dependencies make sure you click on Pub Get.

In our main.dart file we will be defining the initial route, routes and navigation for navigating to other pages by using dart maps.

Here’s how our main.dart file would look like-

import 'package:flutter/material.dart';
import 'package:firebase_core/firebase_core.dart';
import 'welcome_screen.dart';
import 'home_screen.dart';
import 'signup_screen.dart';
import 'login_screen.dart';

void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(MyApp());
}

class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
initialRoute: 'welcome_screen',
routes: {
'welcome_screen': (context) => WelcomeScreen(),
'registration_screen': (context) => RegistrationScreen(),
'login_screen': (context) => LoginScreen(),
'home_screen': (context) => HomeScreen()
},
);
}
}

Now we need to design a welcome screen for the user to either direct the user to the login screen page or the sign-up/register screen page.

We can design the UI for our screen somewhat like this-

You might use a Flat button or you can make a customized button like I have and use that instead.

Here is the code for the customized button if you want to use it in your code.

import 'package:flutter/material.dart';

class RoundedButton extends StatelessWidget {
RoundedButton(
{@required this.colour, @required this.title, @required this.onPressed});
final Color colour;
final String title;
final Function onPressed;
@override
Widget build(BuildContext context) {
return Padding(
padding: EdgeInsets.symmetric(vertical: 16.0),
child: Material(
elevation: 5.0,
color: colour,
borderRadius: BorderRadius.circular(30.0),
child: MaterialButton(
onPressed: onPressed,
//Go to login screen.
minWidth: 200.0,
height: 42.0,
child: Text(
title,
style: TextStyle(color: Colors.white),
),
),
),
);
}
}

So you can create a separate dart file and use the above code to create your own button.

Here’s the code for our welcome screen-

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

class WelcomeScreen extends StatefulWidget {
@override
_WelcomeScreenState createState() => _WelcomeScreenState();
}

class _WelcomeScreenState extends State<WelcomeScreen> {
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
body: Padding(
padding: EdgeInsets.symmetric(horizontal: 24.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
RoundedButton(
colour: Colors.lightBlueAccent,
title: 'Log In',
onPressed: () {
Navigator.pushNamed(context, 'login_screen');
},
),
RoundedButton(
colour: Colors.blueAccent,
title: 'Register',
onPressed: () {
Navigator.pushNamed(context, 'registration_screen');
}),
]),
));
}
}

Now we before we look into the code for our login and sign up screen we need to do one little thing go to your firebase project and under the authentication tab of your project go to the sign-in method tab and there you find a email/provider tab switch it on and hit save.

Now we will be dealing with the heart of our app that is to creating an account and signing the user in.

In both our sign-up and login page we will have two fields in which the user will enter or create his/her email and password and login into our database. The account details of the user will be stored under the users' tab of our firebase project.

This is how our Sign Up screen would look like-

First let's take a look at the code for our sign up screen-

import 'package:flutter/material.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:modal_progress_hud/modal_progress_hud.dart';
import 'rounded_button.dart';

//code for designing the UI of our text field where the user writes his email id or password

const kTextFieldDecoration = InputDecoration(
hintText: 'Enter a value',
hintStyle: TextStyle(color: Colors.grey),
contentPadding: EdgeInsets.symmetric(vertical: 10.0, horizontal: 20.0),
border: OutlineInputBorder(
borderRadius: BorderRadius.all(Radius.circular(32.0)),
),
enabledBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.lightBlueAccent, width: 1.0),
borderRadius: BorderRadius.all(Radius.circular(32.0)),
),
focusedBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.lightBlueAccent, width: 2.0),
borderRadius: BorderRadius.all(Radius.circular(32.0)),
),
);

class RegistrationScreen extends StatefulWidget {
@override
_RegistrationScreenState createState() => _RegistrationScreenState();
}

class _RegistrationScreenState extends State<RegistrationScreen> {
final _auth = FirebaseAuth.instance;
String email;
String password;
bool showSpinner = false;
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
body: ModalProgressHUD(
inAsyncCall: showSpinner,
child: Padding(
padding: EdgeInsets.symmetric(horizontal: 24.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
TextField(
keyboardType: TextInputType.emailAddress,
textAlign: TextAlign.center,
onChanged: (value) {
email = value;
//Do something with the user input.
},
decoration: kTextFieldDecoration.copyWith(
hintText: 'Enter your email')),
SizedBox(
height: 8.0,
),
TextField(
obscureText: true,
textAlign: TextAlign.center,
onChanged: (value) {
password = value;
//Do something with the user input.
},
decoration: kTextFieldDecoration.copyWith(
hintText: 'Enter your Password')),
SizedBox(
height: 24.0,
),
RoundedButton(
colour: Colors.blueAccent,
title: 'Register',
onPressed: () async {
setState(() {
showSpinner = true;
});
try {
final newUser = await _auth.createUserWithEmailAndPassword(
email: email, password: password);
if (newUser != null) {
Navigator.pushNamed(context, 'home_screen');
}
} catch (e) {
print(e);
}
setState(() {
showSpinner = false;
});
},
)
],
),
),
),
);
}
}

Here we first create a variable _auth for our firebase instance and declare it as final because we won't be changing it at all. This will allow us to work with our firebase authentication procedure and we can now create a user or sign in a user as we have done in the above code segment that we have created a user account, with the function createUserWithEmailAndPassword, now the user can create an email id and password and password for himself. If there is something wrong while creating an account firebase will throw an exception

The code for logging in is the almost identical only difference being here we use the firebase instance to sign the user into our app with the email id and password he has already created and has registered himself on our app.

This is how our login screen would look like-

Here’s the code for our login screen-

import 'package:firebase_auth/firebase_auth.dart';
import 'rounded_button.dart';
import 'package:modal_progress_hud/modal_progress_hud.dart';
import 'package:flutter/material.dart';

//code for designing the UI of our text field where the user writes his email id or password

const kTextFieldDecoration = InputDecoration(
hintText: 'Enter a value',
hintStyle: TextStyle(color: Colors.grey),
contentPadding: EdgeInsets.symmetric(vertical: 10.0, horizontal: 20.0),
border: OutlineInputBorder(
borderRadius: BorderRadius.all(Radius.circular(32.0)),
),
enabledBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.lightBlueAccent, width: 1.0),
borderRadius: BorderRadius.all(Radius.circular(32.0)),
),
focusedBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.lightBlueAccent, width: 2.0),
borderRadius: BorderRadius.all(Radius.circular(32.0)),
));

class LoginScreen extends StatefulWidget {
@override
_LoginScreenState createState() => _LoginScreenState();
}

final _auth = FirebaseAuth.instance;

class _LoginScreenState extends State<LoginScreen> {
String email;
String password;
bool showSpinner = false;
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
body: ModalProgressHUD(
inAsyncCall: showSpinner,
child: Padding(
padding: EdgeInsets.symmetric(horizontal: 24.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
TextField(
keyboardType: TextInputType.emailAddress,
textAlign: TextAlign.center,
onChanged: (value) {
email = value;
//Do something with the user input.
},
decoration: kTextFieldDecoration.copyWith(
hintText: 'Enter your email',
)),
SizedBox(
height: 8.0,
),
TextField(
obscureText: true,
textAlign: TextAlign.center,
onChanged: (value) {
password = value;
//Do something with the user input.
},
decoration: kTextFieldDecoration.copyWith(
hintText: 'Enter your password.')),
SizedBox(
height: 24.0,
),
RoundedButton(
colour: Colors.lightBlueAccent,
title: 'Log In',
onPressed: () async {
setState(() {
showSpinner = true;
});
try {
final user = await _auth.signInWithEmailAndPassword(
email: email, password: password);
if (user != null) {
Navigator.pushNamed(context, 'home_screen');
}
} catch (e) {
print(e);
}
setState(() {
showSpinner = false;
});
}),
],
),
),
),
);
}
}

So with this our procedure of creating a user account on firebase and signing in the user with his credentials is complete.

Now the only thing left is our home screen where the user will be headed after creating an account or logging in. For the purpose of this article, we will keep our home screen relatively simple and it will have just some normal text welcoming the user.

This is our how our home screen will look like-

It will just display at the center of the screen “Welcome User”. Also if you notice there is a cross icon button on the top right corner of our app bar, that will actually sign the user out of our app. I have created a specific function to execute that functionality.

Here’s the code for our home screen-

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

User loggedinUser;

class HomeScreen extends StatefulWidget {
@override
_HomeScreenState createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
final _auth = FirebaseAuth.instance;

void initState() {
super.initState();
getCurrentUser();
}

//using this function you can use the credentials of the user
void getCurrentUser() async {
try {
final user = await _auth.currentUser;
if (user != null) {
loggedinUser = user;
}
} catch (e) {
print(e);
}
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
leading: null,
actions: <Widget>[
IconButton(
icon: Icon(Icons.close),
onPressed: () {
_auth.signOut();
Navigator.pop(context);

//Implement logout functionality
}),
],
title: Text('Home Page'),
backgroundColor: Colors.lightBlueAccent,
),
body: Center(
child: Text(
"Welcome User",
style: TextStyle(fontSize: 20.0, fontWeight: FontWeight.bold),
),
),
);
}
}

So with this our app is done and now we can create a user account and sign the user in or sign out.

You can check out the source code here- https://github.com/harshlohia11/flutter-signup-login.git

This was so cool, right?

That’s the simplest explanation I could write, there are of course the scenes things, but don’t bother yourself with them now.

Thanks for reading.

In the next article, we will discuss how we can sign the user in with his google account!

--

--

Harsh Lohia
Code for Cause

An Aspiring software Engineer, here to pen down some thoughts!