Learn/Firebase Integration/Firebase Authentication

Firebase Authentication

Add email/password and Google sign-in to your app

7 min~5 min read+35 FX

You can read this lesson publicly. Sign in to unlock exercises, quiz, and FX progress tracking.

Table of Contents

  1. 1. Auth Flow Architecture
  2. 2. This Lesson In Simple Words
  3. 3. Your level focus
  4. 4. One practical habit
  5. 5. Deep Understanding Guide
  6. 6. Why this lesson matters
  7. 7. Study flow for better retention
  8. 8. Quick Glossary
  9. 9. Architecture Lens

Having trouble? AI is here to help

Ask context-aware questions about this lesson. Free plan: 5 questions/day. Upgrade to Premium for higher daily limits.

Use the AI button at the bottom of the screen

Firebase Authentication

Firebase Authentication handles the entire user identity flow for your app including sign-up, sign-in, password reset, and session management. It supports multiple sign-in methods such as email and password, Google Sign-In, Apple Sign-In, phone number verification, and anonymous authentication. Firebase Auth also manages user sessions automatically so your app stays logged in across restarts. You can listen to authentication state changes with a stream and reactively update your UI whenever the user signs in or signs out.

dart
1// pubspec.yaml: firebase_auth: ^4.15.0
2import 'package:firebase_auth/firebase_auth.dart';
3
4final auth = FirebaseAuth.instance;
5
6// ── Sign Up ──
7Future<User?> signUp(String email, String password) async {
8 try {
9 final credential = await auth.createUserWithEmailAndPassword(
10 email: email,
11 password: password,
12 );
13 return credential.user;
14 } on FirebaseAuthException catch (e) {
15 if (e.code == 'weak-password') print('Password too weak');
16 if (e.code == 'email-already-in-use') print('Email taken');
17 return null;
18 }
19}
20
21// ── Sign In ──
22Future<User?> signIn(String email, String password) async {
23 try {
24 final credential = await auth.signInWithEmailAndPassword(
25 email: email,
26 password: password,
27 );
28 return credential.user;
29 } on FirebaseAuthException catch (e) {
30 if (e.code == 'user-not-found') print('No user found');
31 if (e.code == 'wrong-password') print('Wrong password');
32 return null;
33 }
34}
35
36// ── Sign Out ──
37Future<void> signOut() async => await auth.signOut();
38
39// ── Auth State Listener ──
40auth.authStateChanges().listen((User? user) {
41 if (user == null) {
42 print('User is signed out');
43 } else {
44 print('User signed in: ${user.email}');
45 }
46});
47
48// ── Current User ──
49final user = auth.currentUser;
50print(user?.email);
51print(user?.uid);

Listen to Auth State

💡 Listen to Auth State

Use the authStateChanges() stream to reactively update your UI when the user signs in or out. Wrap your root widget with a StreamBuilder listening to this stream so the app automatically shows the login screen or home screen based on auth status.

Auth Flow Architecture

Implement auth as a full lifecycle, not only sign in and sign out screens:

  • Input validation layer for email format and password rules.
  • Auth service layer wrapping FirebaseAuth calls and error translation.
  • Session state layer listening to authStateChanges and routing screens.
  • Recovery layer for password reset and expired credential handling.

This architecture keeps UI simple and gives one place to manage security and error behavior.

Authentication Edge Cases

  • User closes app during sign-in request and reopens with partial session state.
  • Network failure during account creation after local validation passes.
  • Email already in use and weak password errors needing friendly messages.
  • Credential revoked remotely while app is still open.
  • User signs out on one device and expects immediate invalidation elsewhere.

Authentication Security Checklist

  • All auth errors are mapped to user-safe messages without leaking internals.
  • Protected routes cannot render unless a valid authenticated user exists.
  • Sign-out clears cached user state and sensitive in-memory data.
  • Password reset and verification email flows are fully tested end to end.
  • Brute-force and suspicious login behavior are monitored in backend logs.

This Lesson In Simple Words

Add email/password and Google sign in to your app. Backend integration connects app actions to real user data and secure business workflows.

Your level focus

Think in architecture, reliability, and team-level maintainability.

One practical habit

Define data model and access rules before writing convenience helper methods.

Deep Understanding Guide

Why this lesson matters

Security and data integrity issues can damage user trust faster than UI bugs.

Study flow for better retention

  1. Separate UI, state, and data boundaries before writing implementation details.
  2. Think from both sides: client UX and backend authorization constraints.
  3. If another developer can read your flow quickly, your design choices are clear.

Common Mistakes To Avoid

  • Trusting client-side checks without enforcing server-side rules.
  • Using broad read/write permissions in Firestore rules.
  • Storing secrets in plain text or unsafe local storage.
  • Not versioning schemas when documents evolve over time.

Practice Sprint (15-25 Minutes)

  • Before running sample code, predict output and behavior in one sentence.
  • Write one secure Firestore rule and test allow/deny cases.
  • Map one backend document model to a typed client model.
  • Implement auth-state based screen routing with guarded actions.
  • Complete the required exercises without using hints on the first attempt.
  • Answer this question out loud before checking quiz options: "Which method creates a new user with email and password?".

Quick Glossary

  • state: Data that can change and update what the user sees.
  • stream: A sequence of asynchronous values over time.
  • validation: Checks that confirm input is correct before processing.

Code Comprehension Drill

  • State the purpose of the code block in one line before reading details.
  • Mark inputs, state changes, and final output.
  • Change one small value and predict what should happen before running.
  • Run again and compare your prediction with actual behavior.

Architecture Lens

Security rules are part of architecture, not optional deployment polish.

As your app grows, keep UI, state, and data responsibilities separate so each part stays testable and easier to modify.

Lesson Completion Checklist

  • I can explain "Firebase Authentication" in simple words without reading notes.
  • I can describe one real app situation where this concept is required.
  • I know at least one mistake to avoid: Trusting client-side checks without enforcing server-side rules.
  • I can modify one code sample and correctly predict the behavior change.
  • I can finish required exercises with understanding, not trial-and-error guesses.

Frequently Asked Questions

Which method creates a new user with email and password?

createUserWithEmailAndPassword() creates a new Firebase user account with the given email and password.

How do you listen to authentication state changes?

authStateChanges() returns a Stream<User?> that emits whenever the auth state changes (sign in/out).

What does auth.currentUser return when no one is signed in?

currentUser is null when no user is signed in. Always null-check before using it.

Suggest Improvement

Something seems incorrect, unclear, or missing? Let us know.

About The Author

FlutterCraft editorial lessons are reviewed by experienced Flutter developers and updated to stay aligned with modern Flutter and Dart best practices.

Reference docs: Flutter Documentation, Dart Language Tour, and official package documentation where relevant.

Sign in to continue with exercises and quiz for this lesson.

Sign In to Continue