DEV Community

Cover image for Firebase Authentication with GetX in Flutter
Imran Sefat
Imran Sefat

Posted on • Edited on

23 1

Firebase Authentication with GetX in Flutter

Introduction 🎉

You know about GetX. It is an extra-light and robust solution for Flutter. It combines high-performance state management, intelligent dependency injection, and route management quickly and practically.



I won

I’m going to be honest; I’m not that pro at using GetX. So one day, I wanted to use GetX to make a flutter app with firebase authentication to understand better, but I was confused. Then it took me some time to figure out how it was working, and eventually, I succeeded and fell in love with the world of GetX.



I won

Let’s Get Started 🎯

I will assume that you have a starter template setup to enter email, password, or a button to login with Gmail. Let’s list the steps necessary to make the authentication process.



Steps 👣

1. Configuring the Flutter Project

2. Connect App to Firebase

3. Creating the Auth Controller

4. Inject the auth controller

5. Login or Signing up Users

6. Success



I won

1. Configuring the Flutter project ⚙️

Let’s add the necessary packages that we’re going to use throughout the application.

Copy the dependencies to your Pubspec.yaml file. I am using the latest version available now at this moment.latest version available now at this moment.

dependencies:
cupertino_icons: ^1.0.2
firebase_auth: ^3.1.3
firebase_core: ^1.7.0
flutter:
sdk: flutter
get: ^4.3.8
google_sign_in: ^5.1.1
dev_dependencies:
flutter_lints: ^1.0.0
flutter_test:
sdk: flutter
view raw Pubspec.yaml hosted with ❤ by GitHub


2. Connect App to Firebase 🤝

Now we have to connect our app to firebase. First, go to the firebase console and create your project if you haven’t already. You will see an option to add an app to firebase. Depending on your preference and requirement, do that. The steps are pretty straightforward, and firebase will show you what to do and how.



Firebase Console

Don’t forget to enable the Email/Password Sign in and Google Sign In methods.



Sign In Method

3. Creating the Auth Controller 🎮

First, let’s make a constant file for the sake of simplicity and not to get confused or code duplications. Copy the below codes and paste them into your dart file inside the lib folder.

Suggestion: Make a folder inside of the lib folder titled Constants.

AuthController authController = AuthController.instance;
final Future<FirebaseApp> firebaseInitialization = Firebase.initializeApp();
FirebaseAuth auth = FirebaseAuth.instance;
FirebaseFirestore firebaseFirestore = FirebaseFirestore.instance;
GoogleSignIn googleSign = GoogleSignIn();




Now let’s create the Auth Controller where all of our business login related to Firebase Authentication will work. Just copy the below codes and paste them into your dart file inside of your lib folder.

Suggestion: Make a folder for titled Controller.

class AuthController extends GetxController {
static AuthController instance = Get.find();
late Rx<User?> firebaseUser;
late Rx<GoogleSignInAccount?> googleSignInAccount;
@override
void onReady() {
super.onReady();
// auth is comning from the constants.dart file but it is basically FirebaseAuth.instance.
// Since we have to use that many times I just made a constant file and declared there
firebaseUser = Rx<User?>(auth.currentUser);
googleSignInAccount = Rx<GoogleSignInAccount?>(googleSign.currentUser);
firebaseUser.bindStream(auth.userChanges());
ever(firebaseUser, _setInitialScreen);
googleSignInAccount.bindStream(googleSign.onCurrentUserChanged);
ever(googleSignInAccount, _setInitialScreenGoogle);
}
_setInitialScreen(User? user) {
if (user == null) {
// if the user is not found then the user is navigated to the Register Screen
Get.offAll(() => const Register());
} else {
// if the user exists and logged in the the user is navigated to the Home Screen
Get.offAll(() => Home());
}
}
_setInitialScreenGoogle(GoogleSignInAccount? googleSignInAccount) {
print(googleSignInAccount);
if (googleSignInAccount == null) {
// if the user is not found then the user is navigated to the Register Screen
Get.offAll(() => const Register());
} else {
// if the user exists and logged in the the user is navigated to the Home Screen
Get.offAll(() => Home());
}
}
void signInWithGoogle() async {
try {
GoogleSignInAccount? googleSignInAccount = await googleSign.signIn();
if (googleSignInAccount != null) {
GoogleSignInAuthentication googleSignInAuthentication =
await googleSignInAccount.authentication;
AuthCredential credential = GoogleAuthProvider.credential(
accessToken: googleSignInAuthentication.accessToken,
idToken: googleSignInAuthentication.idToken,
);
await auth
.signInWithCredential(credential)
.catchError((onErr) => print(onErr));
}
} catch (e) {
Get.snackbar(
"Error",
e.toString(),
snackPosition: SnackPosition.BOTTOM,
);
print(e.toString());
}
}
void register(String email, password) async {
try {
await auth.createUserWithEmailAndPassword(
email: email, password: password);
} catch (firebaseAuthException) {}
}
void login(String email, password) async {
try {
await auth.signInWithEmailAndPassword(email: email, password: password);
} catch (firebaseAuthException) {}
}
void signOut() async {
await auth.signOut();
}
}


4. Inject the Auth Controller 💉

We have created the Auth Controller, but how are we going to use it? Let’s hop into the main.dart file and make some changes to our code.

void main() async {
WidgetsFlutterBinding.ensureInitialized();
await firebaseInitialization.then((value) {
Get.put(AuthController());
});
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return GetMaterialApp(
debugShowCheckedModeBanner: false,
title: 'Flutter Demo',
theme: ThemeData.dark(),
// we don't really have to put the home page here
// GetX is going to navigate the user and clear the navigation stack
home: const CircularProgressIndicator(),
);
}
}
view raw main.dart hosted with ❤ by GitHub


Here, we are initializing the firebase and injecting the AuthController instance in the 4th line.



Sign In Method

Our dependencies are completed and initialized. Now let’s sign up some users.

5. Login or Signing up Users 🙋‍♂️🙋‍♀️

I assume you have a basic or super beautiful Signup or login screen ready. If not, you can copy my code for the screen, but note that it’s a super simple screen.

class Register extends StatefulWidget {
const Register({Key? key}) : super(key: key);
@override
State<Register> createState() => _RegisterState();
}
class _RegisterState extends State<Register> {
final TextEditingController _emailController = TextEditingController();
final TextEditingController _passwordController = TextEditingController();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("Register"),
),
body: Column(
children: [
TextField(
decoration: const InputDecoration(hintText: "Email"),
controller: _emailController,
),
TextField(
decoration: const InputDecoration(hintText: "Password"),
controller: _passwordController,
obscureText: true,
),
const SizedBox(height: 30),
Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
ElevatedButton(
onPressed: () async {
authController.register(_emailController.text.trim(),
_passwordController.text.trim());
},
child: const Text("Sign Up"),
),
ElevatedButton(
onPressed: () async {
authController.login(_emailController.text.trim(),
_passwordController.text.trim());
},
child: const Text("Login"),
),
],
),
const SizedBox(height: 30),
ElevatedButton(
style: ElevatedButton.styleFrom(
primary: Colors.red,
),
onPressed: () {
authController.signInWithGoogle();
},
child: const Text("Sign In with Google"),
),
],
),
);
}
}
view raw register.dart hosted with ❤ by GitHub


The above code is pretty self-explanatory. There are just two (2) text fields for email and password, one button to login and one to Register / Signup. The last elevated button is for the google authentication popup.

6. Success 🎉

You just implemented Firebase Authentication in Flutter with GetX.

I have a Youtube Channel Named “Coding with Imran”

Do subscribe to my channel if you want to get future updates!

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (13)

Collapse
 
bigbott profile image
bigbott

Nice article.
Especially I like the part when controller decides where to go. Clever.
But I have a doubt about making navigation from controllers. It makes code much less readable.
Also, you don't need to clear stack from the beginning, since there is nothing in stack. But this is not important detail.
Thanks for sharing.

Collapse
 
imransefat profile image
Imran Sefat

Hey thanks for your comment. It's been so long I worked with getx but I had a look at the code after reading your comment. I agree with the code not being readable about the navigation controller but it's probably because of handling all the state but I'm not too sure as I worked on it years ago.

Also, I cleared the navigation as the time I wrote this article, I thought of user credential issues like a token can be expired or something and that can be an issue with the navigation stack cause you don't want your user to be getting back to the Dashboard page after you navigated them from Dashboard to the Register page. This is just an assumption as I wrote this years ago and don't remember every details.

Cheers

Collapse
 
shah000 profile image
HUSSAIN SHAH

thanks but one question for you ..
how do we execute two function in single(login/Register) button pressed in flutter?

Collapse
 
cris96174560 profile image
Cris

Hello, I had a problem with the signOut method. It says it is not implemented. I'm using
firebase_auth: ^3.2.0
firebase_core: ^1.10.0

Would appreciate any help

Collapse
 
imransefat profile image
Imran Sefat

Please check if you have imported the files correctly or check whether you have copied the signout function or not.

void signOut() async {
await auth.signOut();
}

Check if the above function is present in the auth_controller.dart file

Collapse
 
cris96174560 profile image
Cris

Yes. Thanks for the reply
I traced the function all the way to
.../snap/flutter/common/flutter/.pub-cache/hosted/pub.dartlang.org/firebase_auth_platform_interface-6.1.4/lib/src/platform_interface/platform_interface_firebase_auth.dart

this is its code:

Future signOut() async {
throw UnimplementedError('signOut() is not implemented');
}

Collapse
 
idaudk profile image
Daud K

bro, can you provide guide for facebook and forget password feature.

Collapse
 
imransefat profile image
Imran Sefat

It's mostly the same for the Facebook authentication. You will be needing the flutter_facebook_auth package which can be found here: pub.dev/packages/flutter_facebook_...

a sample sign in function is given below:

Future signInWithFacebook() async {
// Trigger the sign-in flow
final LoginResult loginResult = await FacebookAuth.instance.login();

// Create a credential from the access token
final OAuthCredential facebookAuthCredential = FacebookAuthProvider.credential(loginResult.accessToken.token);

// Once signed in, return the UserCredential
return FirebaseAuth.instance.signInWithCredential(facebookAuthCredential);
}

I will try to make a video or write an article for the auth process including the password reset functions.

Collapse
 
ankita_tripathi_5cdae815b profile image
Ankita Tripathi

This is by far the most sorted article on using GetX! Would you like to submit this article on Dev Library as well? devlibrary.withgoogle.com/

Collapse
 
imransefat profile image
Imran Sefat

Thanks for being so kind.
Yes, I will be glad to submit there as well.

Collapse
 
dbestech profile image
dbestech
Comment hidden by post author
Collapse
 
mdusaama0 profile image
mdusaama0

when app is running sometime it navigates to home screen automatically.
Console Log:
D/FirebaseAuth( 2968): Notifying id token listeners about user ( mjnetiCUregDma3eBECG79vyU9p2 ).

Collapse
 
whoadityanawandar profile image
Aditya B Nawandar

How do you make this role based?

Some comments have been hidden by the post's author - find out more

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay