Firebase Authentication helps you easily add user sign-in to your app. It keeps user info safe and lets users log in quickly.
Firebase Authentication in Flutter
final FirebaseAuth auth = FirebaseAuth.instance; // Sign up with email and password UserCredential userCredential = await auth.createUserWithEmailAndPassword( email: 'email@example.com', password: 'password123', ); // Sign in with email and password UserCredential userCredential2 = await auth.signInWithEmailAndPassword( email: 'email@example.com', password: 'password123', ); // Sign out await auth.signOut();
Use FirebaseAuth.instance to access authentication methods.
All sign-in and sign-up methods return a UserCredential object with user info.
final auth = FirebaseAuth.instance; // Sign up new user await auth.createUserWithEmailAndPassword( email: 'user@example.com', password: 'mypassword', );
final auth = FirebaseAuth.instance; // Sign in existing user await auth.signInWithEmailAndPassword( email: 'user@example.com', password: 'mypassword', );
final auth = FirebaseAuth.instance; // Sign out current user await auth.signOut();
This app lets users sign up, sign in, and sign out using Firebase Authentication with email and password. It shows messages for success or failure.
import 'package:flutter/material.dart'; import 'package:firebase_core/firebase_core.dart'; import 'package:firebase_auth/firebase_auth.dart'; void main() async { WidgetsFlutterBinding.ensureInitialized(); await Firebase.initializeApp(); runApp(MyApp()); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( home: AuthExample(), ); } } class AuthExample extends StatefulWidget { @override _AuthExampleState createState() => _AuthExampleState(); } class _AuthExampleState extends State<AuthExample> { final FirebaseAuth _auth = FirebaseAuth.instance; final TextEditingController _emailController = TextEditingController(); final TextEditingController _passwordController = TextEditingController(); String _message = ''; Future<void> _signUp() async { try { await _auth.createUserWithEmailAndPassword( email: _emailController.text.trim(), password: _passwordController.text.trim(), ); setState(() { _message = 'Sign up successful!'; }); } catch (e) { setState(() { _message = 'Sign up failed: $e'; }); } } Future<void> _signIn() async { try { await _auth.signInWithEmailAndPassword( email: _emailController.text.trim(), password: _passwordController.text.trim(), ); setState(() { _message = 'Sign in successful!'; }); } catch (e) { setState(() { _message = 'Sign in failed: $e'; }); } } Future<void> _signOut() async { await _auth.signOut(); setState(() { _message = 'Signed out'; }); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: Text('Firebase Auth Example')), body: Padding( padding: EdgeInsets.all(16), child: Column( children: [ TextField( controller: _emailController, decoration: InputDecoration(labelText: 'Email'), keyboardType: TextInputType.emailAddress, ), TextField( controller: _passwordController, decoration: InputDecoration(labelText: 'Password'), obscureText: true, ), SizedBox(height: 20), Row( mainAxisAlignment: MainAxisAlignment.spaceAround, children: [ ElevatedButton(onPressed: _signUp, child: Text('Sign Up')), ElevatedButton(onPressed: _signIn, child: Text('Sign In')), ElevatedButton(onPressed: _signOut, child: Text('Sign Out')), ], ), SizedBox(height: 20), Text(_message, style: TextStyle(color: Colors.blue)), ], ), ), ); } }
Always initialize Firebase before using authentication.
Use try-catch to handle errors like wrong password or user not found.
Keep user passwords safe by never storing them yourself; Firebase handles this securely.
Firebase Authentication makes adding user login easy and secure.
Use createUserWithEmailAndPassword to sign up and signInWithEmailAndPassword to log in.
Always handle errors and show clear messages to users.
Practice
Solution
Step 1: Understand Firebase Authentication role
Firebase Authentication helps apps manage user accounts securely.Step 2: Differentiate from other Firebase services
It does not store user data or handle UI or notifications.Final Answer:
To securely manage user sign-up and login -> Option BQuick Check:
Authentication = Secure login [OK]
- Confusing authentication with database storage
- Thinking it handles UI design
- Assuming it sends notifications
Solution
Step 1: Identify sign-up method
The method to create a new user iscreateUserWithEmailAndPassword.Step 2: Differentiate from sign-in and other methods
signInWithEmailAndPasswordis for login, not sign-up.Final Answer:
createUserWithEmailAndPassword -> Option AQuick Check:
Sign-up method = createUserWithEmailAndPassword [OK]
- Using signInWithEmailAndPassword for sign-up
- Confusing signOut with sign-up
- Mixing reset email with sign-up
try {
await FirebaseAuth.instance.signInWithEmailAndPassword(email: 'user@example.com', password: 'pass123');
print('Login successful');
} catch (e) {
print('Login failed');
}Solution
Step 1: Analyze try block with correct credentials
Since email and password are correct, signInWithEmailAndPassword succeeds.Step 2: Check catch block execution
No error occurs, so catch block is skipped and 'Login successful' prints.Final Answer:
Login successful -> Option DQuick Check:
Correct login prints success [OK]
- Assuming catch block runs on success
- Thinking syntax error occurs
- Ignoring async/await behavior
final user = await FirebaseAuth.instance.createUserWithEmailAndPassword(email: email, password: password); print(user.email);
Solution
Step 1: Check return type of createUserWithEmailAndPassword
This method returns a UserCredential object, not a User directly.Step 2: Access user email correctly
The email is inside user.user.email, so printing user.email causes error.Final Answer:
createUserWithEmailAndPassword returns UserCredential, not User -> Option AQuick Check:
Return type is UserCredential [OK]
- Treating UserCredential as User
- Forgetting to access .user property
- Misusing await keyword
try {
await FirebaseAuth.instance.signInWithEmailAndPassword(email: email, password: password);
} catch (e) {
if (e.code == 'wrong-password') {
print('Incorrect password. Please try again.');
} else {
print('Login error: ' + e.message);
}
}Solution
Step 1: Understand error handling in Firebase Auth
FirebaseAuthException provides the code property; generic catch (e) may not.Step 2: Use specific catch for FirebaseAuthException
Usingon FirebaseAuthException catch (e)allows access to e.code safely.Step 3: Evaluate given code
Given code uses generic catch, so e.code may cause runtime error.Final Answer:
Should use on FirebaseAuthException catch instead of generic catch -> Option CQuick Check:
Use FirebaseAuthException catch for error codes [OK]
- Using generic catch without exception type
- Assuming all exceptions have code property
- Replacing print with throw unnecessarily
Ready to prove it?
Pass the test and this pattern moves unknown
