How to Use Firebase Auth in Flutter: Simple Guide
To use
FirebaseAuth in Flutter, first add the firebase_auth package and initialize Firebase in your app. Then, use FirebaseAuth.instance to sign up, sign in, or sign out users with methods like createUserWithEmailAndPassword and signInWithEmailAndPassword.Syntax
Here is the basic syntax to use Firebase Authentication in Flutter:
FirebaseAuth.instance: Access the Firebase Auth service.createUserWithEmailAndPassword(email, password): Register a new user.signInWithEmailAndPassword(email, password): Sign in an existing user.signOut(): Log out the current user.
dart
final FirebaseAuth auth = FirebaseAuth.instance; // Register user await auth.createUserWithEmailAndPassword( email: 'user@example.com', password: 'password123' ); // Sign in user await auth.signInWithEmailAndPassword( email: 'user@example.com', password: 'password123' ); // Sign out user await auth.signOut();
Example
This example shows a simple Flutter app that lets a user sign in with email and password using Firebase Auth.
dart
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: SignInPage(), ); } } class SignInPage extends StatefulWidget { @override _SignInPageState createState() => _SignInPageState(); } class _SignInPageState extends State<SignInPage> { final FirebaseAuth _auth = FirebaseAuth.instance; final TextEditingController _emailController = TextEditingController(); final TextEditingController _passwordController = TextEditingController(); String _message = ''; Future<void> _signIn() async { try { await _auth.signInWithEmailAndPassword( email: _emailController.text.trim(), password: _passwordController.text.trim(), ); setState(() { _message = 'Signed in successfully!'; }); } catch (e) { setState(() { _message = 'Error: ' + e.toString(); }); } } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: Text('Firebase Auth Sign In')), body: Padding( padding: EdgeInsets.all(16), child: Column( children: [ TextField( controller: _emailController, decoration: InputDecoration(labelText: 'Email'), ), TextField( controller: _passwordController, decoration: InputDecoration(labelText: 'Password'), obscureText: true, ), SizedBox(height: 20), ElevatedButton( onPressed: _signIn, child: Text('Sign In'), ), SizedBox(height: 20), Text(_message), ], ), ), ); } }
Output
A Flutter app screen with email and password fields, a 'Sign In' button, and a message area showing success or error after sign in attempt.
Common Pitfalls
Common mistakes when using Firebase Auth in Flutter include:
- Not initializing Firebase before using
FirebaseAuth. - Not handling exceptions from sign-in or sign-up methods.
- Using plain text passwords without validation.
- Forgetting to add
firebase_coreandfirebase_authpackages inpubspec.yaml.
dart
/* Wrong: Using FirebaseAuth before Firebase.initializeApp() */ // final auth = FirebaseAuth.instance; // This causes error if Firebase not initialized /* Right: Initialize Firebase first */ await Firebase.initializeApp(); final auth = FirebaseAuth.instance;
Quick Reference
Here is a quick summary of key Firebase Auth methods in Flutter:
| Method | Description |
|---|---|
| createUserWithEmailAndPassword(email, password) | Register a new user with email and password |
| signInWithEmailAndPassword(email, password) | Sign in an existing user |
| signOut() | Sign out the current user |
| currentUser | Get the currently signed-in user |
| sendPasswordResetEmail(email) | Send password reset email |
Key Takeaways
Always initialize Firebase with Firebase.initializeApp() before using FirebaseAuth.
Use FirebaseAuth.instance to access authentication methods like signIn and signUp.
Handle errors with try-catch to manage sign-in failures gracefully.
Add firebase_core and firebase_auth packages to your Flutter project dependencies.
Validate user input before calling authentication methods for better user experience.