Firebase Authentication with Email/Password
Now the real fun begins! We're going to implement the logic for registering new users and logging in existing ones using their email and password. Firebase Auth makes this incredibly simple with just a few method calls.
Why This Topic Matters
Email and password authentication is the most common way users interact with apps. It's the standard for creating a personal account. Understanding how to handle these requests—and more importantly, how to handle the errors that come with them (like "wrong password" or "email already in use")—is vital for a smooth user experience.
How To Study This Chapter
Authentication methods in Firebase are asynchronous. This means they return a Future. You'll need to use async and await to handle these operations. Pay close attention to the try-catch blocks; handling errors gracefully is what separates a good app from a bad one.
Enabling Email/Password Auth
Before writing code, you MUST enable this method in the Firebase Console:
- Go to Authentication > Sign-in method.
- Click Email/Password.
- Enable it and click Save.
Registration Logic
To create a new user, use the createUserWithEmailAndPassword method.
import 'package:firebase_auth/firebase_auth.dart';
Future<void> registerUser(String email, String password) async {
try {
final credential = await FirebaseAuth.instance.createUserWithEmailAndPassword(
email: email,
password: password,
);
print('User registered: ${credential.user?.uid}');
} on FirebaseAuthException catch (e) {
if (e.code == 'weak-password') {
print('The password provided is too weak.');
} else if (e.code == 'email-already-in-use') {
print('The account already exists for that email.');
}
} catch (e) {
print(e);
}
}
Login Logic
To log in an existing user, use the signInWithEmailAndPassword method.
Future<void> loginUser(String email, String password) async {
try {
final credential = await FirebaseAuth.instance.signInWithEmailAndPassword(
email: email,
password: password
);
print('User logged in: ${credential.user?.uid}');
} on FirebaseAuthException catch (e) {
if (e.code == 'user-not-found') {
print('No user found for that email.');
} else if (e.code == 'wrong-password') {
print('Wrong password provided for that user.');
}
}
}
Signing Out
Logging a user out is even simpler.
Future<void> signOut() async {
await FirebaseAuth.instance.signOut();
}
Handling Auth Exceptions
Firebase provides specific error codes for different scenarios. You should always catch FirebaseAuthException to provide meaningful feedback to your users. Common codes include:
invalid-email: The email address is badly formatted.user-disabled: The user account has been disabled.operation-not-allowed: You haven't enabled email/password auth in the console.
In the next chapter, we'll build the UI that actually calls these methods!