Flutter Firebase Authentication Tutorial 2022 using GETX

Basics, Database, Flutter Firebase, Flutter Login App

In this flutter tutorial, we will learn flutter firebase authentication. Using Email and Password, we will use GETX State Management to perform firebase authentication in a flutter.

  • There will be many topics that we will cover in this playlist and they are as follows.
  • Create a user with an email and password
  • Sign In user with email and password
  • Logout the user
  • Keep the firebase user logged in even app closed
  • Keep the separation of concern with a separate Authentication Repository Controller
  • Signup, and login controller with the backend logic.

Step 1: Setup Firebase Authentication

Before directly starting with firebase authentication, you need to have few things up and running.

We are creating Flutter Login App and we have already learned and designed the Login App. You can download the code from here, or watch the playlist here.

Firstly, you have to setup firebase in flutter.

Enable the Email SignIn method in Firebase Console.

Add firebase_auth dependency in the pubspec.ymal file in your flutter project.

Once everything setup, now let’s configure main.dart because whenever our project loads, it should load firebase.

Therefore, we will add WidgetsFlutterBinding.ensureInitialized(); so that our flutter widgets wait until firebase initilization completed and afterwards, we will call the firebase like

Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform);

 

class SignUpFormWidget extends StatelessWidget {
const SignUpFormWidget({
Key? key,
}) : super(key: key);

@override
Widget build(BuildContext context) {
final controller = Get.put(SignUpController());
final _formKey = GlobalKey<FormState>();

return Container(
padding: const EdgeInsets.symmetric(vertical: tFormHeight - 10),
child: Form(
key: _formKey,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
TextFormField(
controller: controller.fullName,
decoration: const InputDecoration(label: Text(tFullName), prefixIcon: Icon(Icons.person_outline_rounded)),
),
const SizedBox(height: tFormHeight - 20),
TextFormField(
controller: controller.email,
decoration: const InputDecoration(label: Text(tEmail), prefixIcon: Icon(Icons.email_outlined)),
),
const SizedBox(height: tFormHeight - 20),
TextFormField(
controller: controller.phoneNo,
decoration: const InputDecoration(label: Text(tPhoneNo), prefixIcon: Icon(Icons.numbers)),
),
const SizedBox(height: tFormHeight - 20),
TextFormField(
controller: controller.password,
decoration: const InputDecoration(label: Text(tPassword), prefixIcon: Icon(Icons.fingerprint)),
),
const SizedBox(height: tFormHeight - 10),
SizedBox(
width: double.infinity,
child: ElevatedButton(
onPressed: () {
if(_formKey.currentState!.validate()){
SignUpController.instance.registerUser(controller.email.text.trim(), controller.password.text.trim());
}
},
child: Text(tSignup.toUpperCase()),
),
)
],
),
),
);
}
}

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

import '../../../repository/authentication_repository/authentication_repository.dart';

class SignUpController extends GetxController {
static SignUpController get instance => Get.find();

//TextField Controllers to get data from TextFields
final email = TextEditingController();
final password = TextEditingController();
final fullName = TextEditingController();
final phoneNo = TextEditingController();

//Call this Function from Design & it will do the rest
void registerUser(String email, String password) {
String? error = AuthenticationRepository.instance.createUserWithEmailAndPassword(email, password) as String?;
if(error != null) {
Get.showSnackbar(GetSnackBar(message: error.toString(),));
}
}

}

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

import '../../../repository/authentication_repository/authentication_repository.dart';

class LoginController extends GetxController {
static LoginController get instance => Get.find();

/// TextField Controllers to get data from TextFields
final email = TextEditingController();
final password = TextEditingController();

/// TextField Validation

//Call this Function from Design & it will do the rest
Future<void> loginUser(String email, String password) async {
String? error = await AuthenticationRepository.instance.loginWithEmailAndPassword(email, password);
if(error != null) {
Get.showSnackbar(GetSnackBar(message: error.toString(),));
}

}
}

import 'package:firebase_auth/firebase_auth.dart';
import 'package:get/get.dart';
import 'package:login_flutter_app/src/features/authentication/screens/welcome/welcome_screen.dart';
import 'package:login_flutter_app/src/features/core/screens/dashboard/dashboard.dart';

import 'exceptions/login_with_email_and_pssword_failure.dart';
import 'exceptions/signup_email_password_failure.dart';

class AuthenticationRepository extends GetxController {
static AuthenticationRepository get instance => Get.find();

//Variables
final _auth = FirebaseAuth.instance;
late final Rx<User?> firebaseUser;

//Will be load when app launches this func will be called and set the firebaseUser state
@override
void onReady() {
firebaseUser = Rx<User?>(_auth.currentUser);
firebaseUser.bindStream(_auth.userChanges());
ever(firebaseUser, _setInitialScreen);
}

/// If we are setting initial screen from here
/// then in the main.dart => App() add CircularProgressIndicator()
_setInitialScreen(User? user) {
user == null ? Get.offAll(() => const WelcomeScreen()) : Get.offAll(() => const Dashboard());
}

//FUNC
Future<String?> createUserWithEmailAndPassword(String email, String password) async {
try {
await _auth.createUserWithEmailAndPassword(email: email, password: password);
firebaseUser.value != null ? Get.offAll(() => const Dashboard()) : Get.to(() => const WelcomeScreen());
} on FirebaseAuthException catch (e) {
final ex = SignUpWithEmailAndPasswordFailure.code(e.code);
return ex.message;
} catch (_) {
const ex = SignUpWithEmailAndPasswordFailure();
return ex.message;
}
return null;
}

Future<String?> loginWithEmailAndPassword(String email, String password) async {
try {
await _auth.signInWithEmailAndPassword(email: email, password: password);
} on FirebaseAuthException catch (e) {
final ex = LogInWithEmailAndPasswordFailure.fromCode(e.code);
return ex.message;
} catch (_) {
const ex = LogInWithEmailAndPasswordFailure();
return ex.message;
}
return null;
}

Future<void> logout() async => await _auth.signOut();
}

6 – Clean Code

So far we were creating everything inside dashboard.dart but at the end you will see our code size has increased alot and become unmanageable.

Therefore, we have to convert our code into separate Custom widgets.

Let's Connect

Videos are always a better source for in-depth knowledge. So, connect with me at YouTube.

Download Project

Flutter Login App UI Source Code- How to Create a complete Flutter app - Flutter education app - Flutter app UI Design - Flutter Course - Flutter Complete App 2022
Dashboard Source COde - Dashboard design in flutter - flutter dashoard - flutter app design 2022 - Flutter UI - Flutter homepage

Latest Courses

Flutter Login App UI Source Code- How to Create a complete Flutter app - Flutter education app - Flutter app UI Design - Flutter Course - Flutter Complete App 2022
Learn flutter from scratch in 4 hours - Flutter Crash Course - Coding with T

Latest Tutorials

Flutter Profile page UI Design - Flutter app design 2023 - Profile Screen Flutter UI - Flutter 2023
Flutter Firebase phone authentication - Firebase Phone auth tutorial in flutter - Flutter Firebase phone number authentication 2022
Firebase Authentication in flutter - Flutter firebase authentication 2022 - firebase auth tutorial 2022 - firebase flutter auth
How to setup firebase in flutter 2022 - Flutter firebase setup
Dashboard Source COde - Dashboard design in flutter - flutter dashoard - flutter app design 2022 - Flutter UI - Flutter homepage

Join Our Mailing List

Join our mailing list to receive the latest, Free Courses, Video Tutorials, free codes and updates regarding Tutorials and services. You will also start getting coupons on the related services.

You have Successfully Subscribed!

FLUTTER APP

Learn Flutter App development from scratch. Create LOGIN APP that can be used with any application which requires Login Sign Up functionality.

You can watch it on YouTube or read and get source code from Blog Post.

You have Successfully Subscribed!