Advanced
Integrating Firebase Authentication in Flutter
· 10 min read
Setup
After adding the firebase_core and firebase_auth packages and generating the platform configuration with the FlutterFire CLI, you need to call Firebase.initializeApp() right at the start of your app. Trying to access any Firebase service, such as FirebaseAuth.instance, before this step completes will throw an error:
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform);
runApp(const MyApp());
}Email/Password Sign-Up and Sign-In
createUserWithEmailAndPassword creates a new account, and signInWithEmailAndPassword signs in to an existing one. Both methods return a Future<UserCredential> and throw a FirebaseAuthException on failure:
class AuthRepository {
AuthRepository(this._auth);
final FirebaseAuth _auth;
Future<void> signUp(String email, String password) async {
await _auth.createUserWithEmailAndPassword(
email: email,
password: password,
);
}
Future<void> signIn(String email, String password) async {
await _auth.signInWithEmailAndPassword(
email: email,
password: password,
);
}
Future<void> signOut() => _auth.signOut();
}Note: never log the email or password, and never send them to an external service like Crashlytics. For debugging, it's safe to log only the code field of the FirebaseAuthException (for example, "wrong-password").
Tracking Session State: authStateChanges()
FirebaseAuth.instance.authStateChanges() is a Stream that emits a User? value whenever the user signs in, signs out, or the token expires. Driving the whole app's routing off this stream is more reliable than maintaining a manual "is logged in" flag:
StreamBuilder<User?>(
stream: FirebaseAuth.instance.authStateChanges(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return const SplashScreen();
}
final user = snapshot.data;
return user == null ? const LoginPage() : const HomePage();
},
)Showing Error Codes to the User Meaningfully
The code field of a FirebaseAuthException gives the reason for the error as a machine-readable string. Instead of showing this directly to the user, map the known codes to localized, understandable messages:
String mapAuthError(FirebaseAuthException e) {
switch (e.code) {
case 'user-not-found':
case 'wrong-password':
case 'invalid-credential':
return 'Incorrect email or password.';
case 'email-already-in-use':
return 'This email address is already in use.';
case 'weak-password':
return 'The password must be at least 6 characters.';
case 'too-many-requests':
return 'Too many attempts, please try again later.';
default:
return 'Something went wrong, please try again.';
}
}Auth Guard With go_router
To block a signed-out user from reaching protected pages, go_router's redirect callback can be combined with authStateChanges (you can find more detail on go_router itself in our article "Navigation Management in Flutter with go_router"):
GoRouter(
redirect: (context, state) {
final loggedIn = FirebaseAuth.instance.currentUser != null;
final loggingInRoute = state.matchedLocation == '/login';
if (!loggedIn && !loggingInRoute) return '/login';
if (loggedIn && loggingInRoute) return '/';
return null;
},
refreshListenable: GoRouterRefreshStream(
FirebaseAuth.instance.authStateChanges(),
),
routes: [
GoRoute(path: '/login', builder: (context, state) => const LoginPage()),
GoRoute(path: '/', builder: (context, state) => const HomePage()),
],
)refreshListenable matters here: it makes go_router re-run the redirect function every time the authStateChanges stream fires; otherwise the router won't automatically send the user to the login page when they sign out.
Things to Watch Out For
1. Never Log Sensitive Data
Don't send values like the password, email, or ID token to print(), debugPrint(), or a third-party analytics service. In production, logs like these become a source of leaks.
2. Store Session Data Securely
firebase_auth stores session data in its own secure storage mechanism (Keychain/Keystore depending on the platform); if you need to store an extra token manually, use flutter_secure_storage instead of SharedPreferences.
3. Don't Forget Email Verification
createUserWithEmailAndPassword creates the account but doesn't automatically verify the email. If you need it, call sendEmailVerification() and check the emailVerified field to restrict unverified accounts.
Conclusion
firebase_auth handles email/password authentication with little code; the real work is wiring the authStateChanges stream correctly into the app's routing logic and showing error codes to the user in a meaningful way. Not logging sensitive data and storing session data securely are two basic rules you shouldn't skip before going to production.