How do you implement Firebase Authentication in Flutter?
Short Answer
Add the `firebase_auth` package, initialize Firebase in `main()`, then use `FirebaseAuth.instance` to sign users in (email/password, Google, etc.) and listen to `authStateChanges()` to react to login/logout across the app.
After running `flutterfire configure` (which wires up your platform-specific Firebase config files) and calling `Firebase.initializeApp()` before `runApp()`, authentication itself is mostly calling methods on `FirebaseAuth.instance`: `createUserWithEmailAndPassword()`, `signInWithEmailAndPassword()`, or a provider-specific sign-in (e.g. Google Sign-In, which gets an OAuth credential and passes it to `signInWithCredential()`).
The key architectural piece is `FirebaseAuth.instance.authStateChanges()`, a Stream that emits the current `User?` (null when signed out) immediately and on every login/logout. Wrapping your app's root in a `StreamBuilder` on this stream is the standard way to route between a login screen and the main app reactively, without manually tracking auth state yourself.
Code Example
StreamBuilder<User?>(
stream: FirebaseAuth.instance.authStateChanges(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return const SplashScreen();
}
return snapshot.hasData ? const HomeScreen() : const LoginScreen();
},
)Common Mistakes
- ×Calling `Firebase.initializeApp()` after `runApp()` instead of before, causing a race condition on startup.
- ×Manually polling `FirebaseAuth.instance.currentUser` instead of listening to `authStateChanges()`.
Related Questions
What's the difference between Firestore and the Realtime Database?
Firestore is a newer, document/collection-based database with richer querying, automatic multi-region scaling, and better offline support; the Realtime Database is a simpler single JSON tree, cheaper for very high-frequency small writes but with weaker querying.
How do push notifications work with Firebase Cloud Messaging in Flutter?
The app registers with FCM to get a unique device token, your backend (or Firebase console) sends a message to that token via the FCM API, and the `firebase_messaging` package delivers it to the app in foreground, background, or terminated states via different handlers.