Flutter Firebase Authentication Tutorial

Authentication is undoubtedly one of the most important feature of any modern application. Firebase makes it really easier for us to add authentication functionality in our app. Here’s a simple guide on how to add Firebase authentication to your app.
If you follow this guide step by step, you don’t need to follow any other tutorials.
- Go to https://console.firebase.google.com/u/0/
- Hit Add Project Button.

3. Give the project name. Continue. Agree to terms of service. You’ll be landed to the project dashboard.

4. Go to Authentication Menu in the left sidebar.

5. Go to SignIn Method

6. Choose the desired Sign-In provider. Here we are going to choose Google as it’s the most popular login method for android.

7. Go to project settings .

8. Go to Your App Section and Add an android App.

9. Fill in the necessary fields.
For Package Name :
Go to your flutter project and find the app/build.gradle.
There you’ll find the package Name.
For App Nickname,
Fill in anything you want.
For SHA-1 signing cert:
(Although it’s optional for other services, it’s mandatory for consuming authentication services).
Enter the code below in your terminal to get the SHA-1 hash. Copy the hash from the terminal to the signing cert. field.
keytool -list -v -keystore "C:\Users\<YOUR USERNAME>\.android\debug.keystore" -alias androiddebugkey -storepass android -keypass android
Here’s the output of the above command,

10. Fill the form.

You can also add fingerprint later on, from here.

11. Download config file and paste it to android/app/google-services.json.

12. Follow this guide to add necessary imports.
In build.gradle, (project)
classpath 'com.google.gms:google-services:4.3.8'

In- app/build.gradle, add the given code as in the screenshot.
apply plugin: 'com.android.application' // Add this line apply plugin: 'com.google.gms.google-services' dependencies { // Import the Firebase BoM implementation platform('com.google.firebase:firebase-bom:28.0.1') // Add the dependency for the Firebase SDK for Google Analytics // When using the BoM, don't specify versions in Firebase dependencies implementation 'com.google.firebase:firebase-analytics' // Add the dependencies for any other desired Firebase products // https://firebase.google.com/docs/android/setup#available-libraries }

Your preparation is done.
Now let’s start the coding part,
- Go to your pubspec.yaml file and add
google_sign_in,get_it as the dependency.
as dependency.

We are going to use GetIt for state management which service locator pattern to keep the logged-in state throughout our app screens.
Create a file named AuthService.dart and put the contents as below.
import 'package:flutter/foundation.dart'; import 'package:google_sign_in/google_sign_in.dart';
class AuthService extends ChangeNotifier { bool _isLoggedIn = false; late GoogleSignInAccount? _loggedInUser; GoogleSignIn googleSignIn = GoogleSignIn();
bool get isLoggedIn => _isLoggedIn; GoogleSignInAccount? get loggedInUser => _loggedInUser;
Future<bool> loginOutWithGoogle() async { try { await googleSignIn.signOut(); _isLoggedIn = false; _loggedInUser = null; notifyListeners(); return true; } catch (ex) { _isLoggedIn = true; notifyListeners(); return false; } }
void setLoggedInUser(GoogleSignInAccount account) { this._loggedInUser = account; notifyListeners(); }
Future<GoogleSignInAccount?> loginWithGoogle() async { return await googleSignIn.signIn(); } }
Create a file named NavigationService.dart and add the code as below.
import 'package:flutter/material.dart';
class NavigationService { final GlobalKey<NavigatorState> navigatorKey = new GlobalKey<NavigatorState>(); Future<dynamic> navigateTo(String routeName) { return navigatorKey.currentState!.pushNamed(routeName); }
Future<dynamic> replaceTo(String routeName) { return navigatorKey.currentState!.pushReplacementNamed(routeName); }
void goBack() { return navigatorKey.currentState!.pop(); } }
Create a file named locator.dart and put the content’s as below.
import 'package:firebaseapp/authservice.dart'; import 'package:get_it/get_it.dart';
import 'homepage.dart'; import 'navigation_service.dart';
GetIt getIt = GetIt.instance;
void setupLocator() { getIt.registerLazySingleton(() => NavigationService()); }
Go to router.dart and add the code as below.
import 'package:firebaseapp/homepage.dart'; import 'package:firebaseapp/signin_page.dart'; import 'package:flutter/material.dart'; import 'package:flutter/widgets.dart';
import 'googlesignin.dart';
class AppRouter { static Route<dynamic> generateRoute(RouteSettings settings) { switch (settings.name) { case '/': return MaterialPageRoute(builder: (_) => HomePage()); case '/signin': return MaterialPageRoute(builder: (_) => SigninPage()); default: return MaterialPageRoute( builder: (_) => Scaffold( body: Center( child: Text('No route defined for ${settings.name}'), ), )); } } }
go to main.dart and add the code as below.
import 'package:firebase_core/firebase_core.dart'; import 'package:flutter/material.dart';
import 'homepage.dart'; import 'locator.dart'; import 'navigation_service.dart'; import "router.dart";
void main() async { WidgetsFlutterBinding.ensureInitialized(); await Firebase.initializeApp(); setupLocator(); runApp(MyApp()); }
class MyApp extends StatelessWidget { // This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, title: 'Flutter Auth App', theme: ThemeData( primarySwatch: Colors.blue, ), home: Homepage(), initialRoute: '/signin', navigatorKey: getIt<NavigationService>().navigatorKey, onGenerateRoute: AppRouter.generateRoute, ); } }
We have 2 widget pages , Homepage and SigninPage. Create the page as desired.
Create the signing page as below,
import 'package:firebaseapp/authservice.dart'; import 'package:flutter/material.dart'; import 'package:google_sign_in/google_sign_in.dart';
import 'locator.dart';
class SigninPage extends StatefulWidget { @override _SigninPageState createState() => _SigninPageState(); }
class _SigninPageState extends State<SigninPage> { final authService = getIt.get<AuthService>(); @override void initState() { super.initState(); authService.addListener(update); }
void update() => setState(() => {});
@override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: Text("Codesundar")), body: Center( child: ElevatedButton( child: Text("Login with Google"), onPressed: () { authService.loginWithGoogle().then((value) { authService.setLoggedInUser(value!); Navigator.pushNamed(context, "/"); }); }, ), ), ), ); } }
Here’s the code for Homepage,
import 'package:flutter/material.dart';
class Homepage extends StatelessWidget { const Homepage({Key key}) : super(key: key);
final authService=getIt<AuthService>(). @override Widget build(BuildContext context) { return Container( child: authService.isLoggedIn ? Column( children: [ Image.network(authService.loggedInUser!.photoUrl!), Text(authService.loggedInUser!.displayName!), Text(authService.loggedInUser!.email), TextButton( onPressed: () { authService.loginOutWithGoogle(); }, child: Text("Logout")) ], ) : Text("Not Logged In") } }
It’s everything you need to do to create a flutter app with google login.