Intégration Firebase
Firebase est une plateforme de développement d'applications mobiles et web fournie par Google. Cette section présentera comment intégrer Firebase dans Flutter.
Présentation de Firebase
Firebase propose une variété de services backend, notamment l'authentification, la base de données, le stockage, l'analyse, et plus encore.
| Services | Description |
|---|---|
| Firebase Auth | Authentification des utilisateurs |
| Cloud Firestore | Base de données NoSQL cloud |
| Realtime Database | Realtime Database |
| Cloud Storage | Stockage de fichiers cloud |
| Firebase Analytics | Analyse des données d'application |
| Fonctions Cloud | Fonctions Cloud sans serveur |
Installation et configuration
Ajouter une dépendance
dependencies: firebase_core: ^2.0.0 firebase_auth: ^4.0.0 cloud_firestore: ^4.0.0
Initialisation de Firebase
Exemple : Initialiser Firebase
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
// Initialiser Firebase
await Firebase.initializeApp();
runApp(const MyApp());
}
import 'package:flutter/material.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
// Initialiser Firebase
await Firebase.initializeApp();
runApp(const MyApp());
}
Firebase Auth - Authentification des utilisateurs
Exemple : Connexion e-mail/mot de passe
import 'package:firebase_auth/firebase_auth.dart';
class AuthService {
final FirebaseAuth _auth = FirebaseAuth.instance;
// Inscription
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('Échec de l’inscription : ${e.message}');
return null;
}
}
// Connexion
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('Échec de la connexion : ${e.message}');
return null;
}
}
// Déconnexion
Future<void> signOut() async {
await _auth.signOut();
}
// Écouter l'état de connexion
Stream<User?> get authStateChanges {
return _auth.authStateChanges();
}
}
class AuthService {
final FirebaseAuth _auth = FirebaseAuth.instance;
// Inscription
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('Échec de l’inscription : ${e.message}');
return null;
}
}
// Connexion
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('Échec de la connexion : ${e.message}');
return null;
}
}
// Déconnexion
Future<void> signOut() async {
await _auth.signOut();
}
// Écouter l'état de connexion
Stream<User?> get authStateChanges {
return _auth.authStateChanges();
}
}
Cloud Firestore - Base de données
Exemple : opérations de base Firestore
import 'package:cloud_firestore/cloud_firestore.dart';
class FirestoreService {
final FirebaseFirestore _db = FirebaseFirestore.instance;
// Ajouter un document
Future<void> addUser(Map<String, dynamic> user) async {
await _db.collection('users').add(user);
// Ou spécifiez un ID
// await _db.collection('users').doc('user_id').set(user);
}
// Obtenir un seul document
Future<Map<String, dynamic>?> getUser(String id) async {
final doc = await _db.collection('users').doc(id).get();
return doc.data();
}
// Récupérer tous les documents de la collection
Future<List<Map<String, dynamic>>> getUsers() async {
final snapshot = await _db.collection('users').get();
return snapshot.docs.map((doc) => doc.data()).toList();
}
// Requête conditionnelle
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();
}
// Mettre à jour le document
Future<void> updateUser(String id, Map<String, dynamic> data) async {
await _db.collection('users').doc(id).update(data);
}
// Supprimer le document
Future<void> deleteUser(String id) async {
await _db.collection('users').doc(id).delete();
}
// Écouteur en temps réel
Stream<QuerySnapshot> watchUsers() {
return _db.collection('users').snapshots();
}
}
class FirestoreService {
final FirebaseFirestore _db = FirebaseFirestore.instance;
// Ajouter un document
Future<void> addUser(Map<String, dynamic> user) async {
await _db.collection('users').add(user);
// Ou spécifiez un ID
// await _db.collection('users').doc('user_id').set(user);
}
// Obtenir un seul document
Future<Map<String, dynamic>?> getUser(String id) async {
final doc = await _db.collection('users').doc(id).get();
return doc.data();
}
// Récupérer tous les documents de la collection
Future<List<Map<String, dynamic>>> getUsers() async {
final snapshot = await _db.collection('users').get();
return snapshot.docs.map((doc) => doc.data()).toList();
}
// Requête conditionnelle
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();
}
// Mettre à jour le document
Future<void> updateUser(String id, Map<String, dynamic> data) async {
await _db.collection('users').doc(id).update(data);
}
// Supprimer le document
Future<void> deleteUser(String id) async {
await _db.collection('users').doc(id).delete();
}
// Écouteur en temps réel
Stream<QuerySnapshot> watchUsers() {
return _db.collection('users').snapshots();
}
}
Firebase Storage - Stockage de fichiers
Exemple : Téléversement de fichier
import 'package:firebase_storage/firebase_storage.dart';
import 'dart:io';
class StorageService {
final FirebaseStorage _storage = FirebaseStorage.instance;
// Téléverser le fichier
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('Échec du téléversement : ${e.message}');
return null;
}
}
// URL de téléchargement du fichier
Future<String?> getDownloadURL(String path) async {
try {
final ref = _storage.ref().child(path);
return await ref.getDownloadURL();
} on FirebaseException catch (e) {
print('Échec de la récupération de l’URL : ${e.message}');
return null;
}
}
// Supprimer le fichier
Future<void> deleteFile(String path) async {
await _storage.ref().child(path).delete();
}
}
import 'dart:io';
class StorageService {
final FirebaseStorage _storage = FirebaseStorage.instance;
// Téléverser le fichier
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('Échec du téléversement : ${e.message}');
return null;
}
}
// URL de téléchargement du fichier
Future<String?> getDownloadURL(String path) async {
try {
final ref = _storage.ref().child(path);
return await ref.getDownloadURL();
} on FirebaseException catch (e) {
print('Échec de la récupération de l’URL : ${e.message}');
return null;
}
}
// Supprimer le fichier
Future<void> deleteFile(String path) async {
await _storage.ref().child(path).delete();
}
}
autres extensionsFirebase offre des services backend puissants et est le meilleur choix pour créer rapidement un backend pour les applications Flutter.