Flutter Firebase Authentication

Most apps need to know who the user is. Authentication answers that question through sign-up, sign-in, and sign-out features. Building a secure login system from scratch is risky: passwords need safe storage, sessions need protection, and reset flows need care. Firebase Authentication hands this work to a service run by Google, and your app calls a handful of simple methods.

How Login Works


  User types email + password
          │
          ▼
  App ── signInWithEmailAndPassword ──→ Firebase Auth
          │                                  │
          │ ←──────── secure token ──────────┘
          ▼
  App stores the signed-in user
  and shows the home screen

Think of a concert wristband. The ticket desk checks your ticket once and gives you a wristband. Every door afterward checks the wristband and never asks for the ticket again. Firebase issues a token that works like that wristband.

Setting Up

  • Create a project in the Firebase console.
  • Enable the Email/Password sign-in method under Authentication.
  • Install the command line tools and connect the app: flutterfire configure.
  • Add the packages:

flutter pub add firebase_core firebase_auth

Initialize Firebase before runApp:


import 'package:firebase_core/firebase_core.dart';
import 'firebase_options.dart';

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform);
  runApp(MyApp());
}

Creating an Account


import 'package:firebase_auth/firebase_auth.dart';

Future<String?> signUp(String email, String password) async {
  try {
    await FirebaseAuth.instance.createUserWithEmailAndPassword(
      email: email,
      password: password,
    );
    return null;
  } on FirebaseAuthException catch (e) {
    return e.code;
  }
}

The function returns null on success and an error code on failure.

Signing In and Out


Future<String?> signIn(String email, String password) async {
  try {
    await FirebaseAuth.instance.signInWithEmailAndPassword(
      email: email,
      password: password,
    );
    return null;
  } on FirebaseAuthException catch (e) {
    return e.code;
  }
}

Future<void> signOut() async {
  await FirebaseAuth.instance.signOut();
}

Friendly Error Messages

Error CodeMessage to Show
invalid-emailThat email address looks wrong.
weak-passwordChoose a longer password.
email-already-in-useAn account with this email exists.
invalid-credentialEmail or password is incorrect.
too-many-requestsToo many attempts. Try again later.
network-request-failedCheck your internet connection.

Never show raw error codes to users. Never reveal whether an email exists in a sign-in failure message, because that detail helps attackers.

Reacting to Login State

The authStateChanges() method returns a stream that fires whenever the user signs in or out. Pair it with StreamBuilder to switch screens automatically.


StreamBuilder<User?>(
  stream: FirebaseAuth.instance.authStateChanges(),
  builder: (context, snapshot) {
    if (snapshot.connectionState == ConnectionState.waiting) {
      return Center(child: CircularProgressIndicator());
    }
    if (snapshot.hasData) {
      return HomeScreen();
    }
    return LoginScreen();
  },
)

  App starts
      │
      ▼
  authStateChanges stream
      │
      ├── user exists ──→ HomeScreen
      └── user is null ─→ LoginScreen

Firebase remembers the user between launches, so people stay signed in after they close the app.

Reading the Current User


final User? user = FirebaseAuth.instance.currentUser;
print(user?.email);
print(user?.uid);

The uid is a unique, permanent identifier. Use it as the key for all of a user's data in your database.

Password Reset and Email Verification


await FirebaseAuth.instance.sendPasswordResetEmail(email: email);

await FirebaseAuth.instance.currentUser?.sendEmailVerification();

Other Sign-In Methods

Firebase supports Google, Apple, phone number, and several other providers. Each one needs its own setup in the console and in the native projects. Apple requires "Sign in with Apple" in iOS apps that offer other third-party login options.

Security and Privacy Practices

  • Enforce a sensible minimum password length in the form and in Firebase settings.
  • Collect only the personal data the app needs.
  • Offer a way to delete the account and its data.
  • Protect database data with security rules that check request.auth.uid.
  • Publish a privacy policy that describes what you collect and why.

Practice Ideas

Build a sign-up screen and a sign-in screen with form validation. Add a sign-out button on the home screen, and watch the auth stream swap the screens. Show a friendly message for each error code in the table.

Passwords: What the App Never Sees

Firebase stores passwords as salted hashes on its own servers. Your app sends the password over an encrypted connection during sign-in and never stores it afterward. Treat that rule as sacred in your own code: never write passwords to logs, never save them in preferences, and never keep them in state longer than the sign-in call. If a teammate asks to store a password for convenience, point them to the persistent session that Firebase already provides.

Designing a Pleasant Login Screen

A good login form lowers friction. Use the right keyboard type for the email field, offer a button that reveals the password, and disable the submit button while the request runs. Place the error message right below the field that caused it. Add a clear link for password reset. These details turn a stressful moment into a quick one.