Firebase Integration
Firebase is a mobile and web application development platform provided by Google. This section will introduce how to integrate Firebase in Flutter.
Firebase Overview
Firebase provides a variety of backend services, including authentication, database, storage, analytics, and more.
| Services | Description |
|---|---|
| Firebase Auth | User authentication |
| Cloud Firestore | Cloud NoSQL Database |
| Realtime Database | Realtime Database |
| Cloud Storage | Cloud file storage |
| Firebase Analytics | Application data analytics |
| Cloud Functions | Cloud Serverless Functions |
Installation and Configuration
Add dependency
dependencies: firebase_core: ^2.0.0 firebase_auth: ^4.0.0 cloud_firestore: ^4.0.0
Firebase initialization
Example: Initialize Firebase
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
// Initialize Firebase
await Firebase.initializeApp();
runApp(const MyApp());
}
import 'package:flutter/material.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
// Initialize Firebase
await Firebase.initializeApp();
runApp(const MyApp());
}
Firebase Auth - User Authentication
Example: Email/password login
import 'package:firebase_auth/firebase_auth.dart';
class AuthService {
final FirebaseAuth _auth = FirebaseAuth.instance;
// Register
Future<User?> registerWithEmail(String email, String password) async {
try {
final credential = await _auth.createUserWithEmailAndPassword(
email: email,
password: password,
);
return credential.user;
} on FirebaseAuthException catch (e) {
print('Registration failed: ${e.message}');
return null;
}
}
// Login
Future<User?> signInWithEmail(String email, String password) async {
try {
final credential = await _auth.signInWithEmailAndPassword(
email: email,
password: password,
);
return credential.user;
} on FirebaseAuthException catch (e) {
print('Login failed: ${e.message}');
return null;
}
}
// Logout
Future<void> signOut() async {
await _auth.signOut();
}
// Listen to login status
Stream<User?> get authStateChanges {
return _auth.authStateChanges();
}
}
class AuthService {
final FirebaseAuth _auth = FirebaseAuth.instance;
// Register
Future<User?> registerWithEmail(String email, String password) async {
try {
final credential = await _auth.createUserWithEmailAndPassword(
email: email,
password: password,
);
return credential.user;
} on FirebaseAuthException catch (e) {
print('Registration failed: ${e.message}');
return null;
}
}
// Login
Future<User?> signInWithEmail(String email, String password) async {
try {
final credential = await _auth.signInWithEmailAndPassword(
email: email,
password: password,
);
return credential.user;
} on FirebaseAuthException catch (e) {
print('Login failed: ${e.message}');
return null;
}
}
// Logout
Future<void> signOut() async {
await _auth.signOut();
}
// Listen to login status
Stream<User?> get authStateChanges {
return _auth.authStateChanges();
}
}
Cloud Firestore - Database
Example: Firestore Basic Operations
import 'package:cloud_firestore/cloud_firestore.dart';
class FirestoreService {
final FirebaseFirestore _db = FirebaseFirestore.instance;
// Add a document
Future<void> addUser(Map<String, dynamic> user) async {
await _db.collection('users').add(user);
// Or specify an ID
// await _db.collection('users').doc('user_id').set(user);
}
// Get a single document
Future<Map<String, dynamic>?> getUser(String id) async {
final doc = await _db.collection('users').doc(id).get();
return doc.data();
}
// Get all documents in the collection
Future<List<Map<String, dynamic>>> getUsers() async {
final snapshot = await _db.collection('users').get();
return snapshot.docs.map((doc) => doc.data()).toList();
}
// Conditional query
Future<List<Map<String, dynamic>>> getUsersByAge(int age) async {
final snapshot = await _db
.collection('users')
.where('age', isGreaterThanOrEqualTo: age)
.get();
return snapshot.docs.map((doc) => doc.data()).toList();
}
// Update document
Future<void> updateUser(String id, Map<String, dynamic> data) async {
await _db.collection('users').doc(id).update(data);
}
// Delete document
Future<void> deleteUser(String id) async {
await _db.collection('users').doc(id).delete();
}
// Real-time listener
Stream<QuerySnapshot> watchUsers() {
return _db.collection('users').snapshots();
}
}
class FirestoreService {
final FirebaseFirestore _db = FirebaseFirestore.instance;
// Add a document
Future<void> addUser(Map<String, dynamic> user) async {
await _db.collection('users').add(user);
// Or specify an ID
// await _db.collection('users').doc('user_id').set(user);
}
// Get a single document
Future<Map<String, dynamic>?> getUser(String id) async {
final doc = await _db.collection('users').doc(id).get();
return doc.data();
}
// Get all documents in the collection
Future<List<Map<String, dynamic>>> getUsers() async {
final snapshot = await _db.collection('users').get();
return snapshot.docs.map((doc) => doc.data()).toList();
}
// Conditional query
Future<List<Map<String, dynamic>>> getUsersByAge(int age) async {
final snapshot = await _db
.collection('users')
.where('age', isGreaterThanOrEqualTo: age)
.get();
return snapshot.docs.map((doc) => doc.data()).toList();
}
// Update document
Future<void> updateUser(String id, Map<String, dynamic> data) async {
await _db.collection('users').doc(id).update(data);
}
// Delete document
Future<void> deleteUser(String id) async {
await _db.collection('users').doc(id).delete();
}
// Real-time listener
Stream<QuerySnapshot> watchUsers() {
return _db.collection('users').snapshots();
}
}
Firebase Storage - File Storage
Example: File upload
import 'package:firebase_storage/firebase_storage.dart';
import 'dart:io';
class StorageService {
final FirebaseStorage _storage = FirebaseStorage.instance;
// Upload file
Future<String?> uploadFile(File file, String path) async {
try {
final ref = _storage.ref().child(path);
final result = await ref.putFile(file);
return await result.ref.getDownloadURL();
} on FirebaseException catch (e) {
print('Upload failed: ${e.message}');
return null;
}
}
// Download file URL
Future<String?> getDownloadURL(String path) async {
try {
final ref = _storage.ref().child(path);
return await ref.getDownloadURL();
} on FirebaseException catch (e) {
print('Failed to get URL: ${e.message}');
return null;
}
}
// Delete file
Future<void> deleteFile(String path) async {
await _storage.ref().child(path).delete();
}
}
import 'dart:io';
class StorageService {
final FirebaseStorage _storage = FirebaseStorage.instance;
// Upload file
Future<String?> uploadFile(File file, String path) async {
try {
final ref = _storage.ref().child(path);
final result = await ref.putFile(file);
return await result.ref.getDownloadURL();
} on FirebaseException catch (e) {
print('Upload failed: ${e.message}');
return null;
}
}
// Download file URL
Future<String?> getDownloadURL(String path) async {
try {
final ref = _storage.ref().child(path);
return await ref.getDownloadURL();
} on FirebaseException catch (e) {
print('Failed to get URL: ${e.message}');
return null;
}
}
// Delete file
Future<void> deleteFile(String path) async {
await _storage.ref().child(path).delete();
}
}
other extensionsFirebase offers powerful backend services and is the best choice for quickly building a backend for Flutter applications.