Flutter
signInWithEmailAndPassword
Sign in with signInWithEmailAndPassword.
signInWithEmailAndPassword
The signInWithEmailAndPassword method signs in a registered user. If the email and password are correct, it returns a UserCredential and currentUser is updated. If the password is wrong, a FirebaseAuthException is thrown.
final cred = await auth.signInWithEmailAndPassword(
email: 'a@b.com',
password: '123456',
);
The signOut method
The signOut method closes the session and currentUser becomes null. You call this method when the user leaves the app or wants to switch to another account. The call is asynchronous, so you await it with await.
await auth.signOut();
print(auth.currentUser); // null
Exercise Sign in and sign out
Get the auth instance, sign in with signInWithEmailAndPassword, print the email. Then call signOut, check currentUser and print 'yok' if it is null.
Show example solution
class User {
final String email;
User(this.email);
}
class UserCredential {
final User user;
UserCredential(this.user);
}
class FirebaseAuth {
static final FirebaseAuth instance = FirebaseAuth._();
FirebaseAuth._();
User? _user;
User? get currentUser => _user;
Future<UserCredential> signInWithEmailAndPassword({
required String email,
required String password,
}) async {
_user = User(email);
return UserCredential(_user!);
}
Future<void> signOut() async {
_user = null;
}
}
void main() async {
final auth = FirebaseAuth.instance;
final cred = await auth.signInWithEmailAndPassword(
email: 'a@b.com',
password: '123456',
);
print(cred.user.email);
await auth.signOut();
print(auth.currentUser?.email ?? 'yok');
}
Test yourself
-
What happens when signInWithEmailAndPassword is given a wrong password?
- The app closes
- An empty UserCredential is returned
- null is returned
- A FirebaseAuthException is thrown
Show answer
A FirebaseAuthException is thrown — When the password is wrong, a FirebaseAuthException is thrown; it does not return null or an empty UserCredential.
-
Call the sign-in method
final cred = await auth.____(
email: 'a@b.com',
password: '123456',
);
Show answer
final cred = await auth.signInWithEmailAndPassword(
email: 'a@b.com',
password: '123456',
);
-
Sign-in and sign-out parts
- signInWithEmailAndPassword
- Signs in
- signOut
- Signs out
- UserCredential
- Sign-in result
- currentUser
- Current user
Next lesson: authStateChanges