Tüm Yazılar
KategoriFlutter
Okuma Süresi
28 dk okuma
Yayın Tarihi
...
Kelime Sayısı
1.728kelime

Kahveni hazırla - bu içerikli bir makale!

Flutter ile Firebase Authentication, Firestore, Cloud Functions, Storage, Analytics ve Crashlytics entegrasyonu. Production-ready Firebase mimarisi.

Flutter Firebase Entegrasyonu: Tam Rehber

Firebase, mobil uygulama gelistirmenin "Isvicre cakisi" olarak biliniyor. Authentication, veritabani, depolama, analytics, crash raporlama ve daha fazlasini tek bir platformda sunuyor. Flutter ile Firebase'i birlestirdiginde, hem iOS hem Android icin production-ready backend altyapisini dakikalar icinde kurabilirsin.

Bu rehberde Firebase'in Flutter ile entegrasyonunu sifirdan production seviyesine kadar ele alacagiz. Her servisin kurulumu, en iyi kullanim sekilleri ve gercek dunya orneklerini inceleyecegiz.

Not: Bu rehber FlutterFire (resmi Flutter Firebase SDK'lari) kullanmaktadir. Tum ornekler Firebase 11.x ve Flutter 3.x ile test edilmistir.

Icindekiler


1. Firebase Kurulumu

FlutterFire CLI ile Otomatik Kurulum

bash
1# FlutterFire CLI yukle
2dart pub global activate flutterfire_cli
3 
4# Firebase projesini baglat
5flutterfire configure --project=my-flutter-app
6 
7# Gerekli paketleri ekle
8flutter pub add firebase_core
9flutter pub add firebase_auth
10flutter pub add cloud_firestore
11flutter pub add firebase_storage
12flutter pub add firebase_analytics
13flutter pub add firebase_crashlytics
dart
1// main.dart - Firebase baslatma
2import 'package:firebase_core/firebase_core.dart';
3import 'package:firebase_crashlytics/firebase_crashlytics.dart';
4import 'package:flutter/foundation.dart';
5import 'package:flutter/material.dart';
6import 'firebase_options.dart';
7 
8Future main() async {
9 WidgetsFlutterBinding.ensureInitialized();
10 
11 await Firebase.initializeApp(
12 options: DefaultFirebaseOptions.currentPlatform,
13 );
14 
15 // Crashlytics: yakalanmamis hatalari otomatik raporla
16 FlutterError.onError = FirebaseCrashlytics.instance.recordFlutterFatalError;
17 PlatformDispatcher.instance.onError = (error, stack) {
18 FirebaseCrashlytics.instance.recordError(error, stack, fatal: true);
19 return true;
20 };
21 
22 runApp(const MyApp());
23}

Firebase Servisleri Karsilastirmasi

Servis
Amac
Ucretsiz Limit
Kullanim
**Authentication**
Kullanici girisi
Sinirsiz
Email, Google, Apple, Phone
**Firestore**
NoSQL veritabani
1GB depolama, 50K okuma/gun
Gercek zamanli veri
**Storage**
Dosya depolama
5GB
Resim, video, dosya
**Functions**
Sunucu kodu
2M cagri/ay
API, webhook, cron
**Analytics**
Kullanim analizi
Sinirsiz
Event, screen tracking
**Crashlytics**
Hata raporlama
Sinirsiz
Crash, non-fatal error
**Remote Config**
Uzaktan ayar
Sinirsiz
Feature flag, A/B test
**FCM**
Push bildirim
Sinirsiz
Bildirim gonderme

2. Authentication

Firebase Auth, kullanici kimlik dogrulamasinin en kolay yoludur:

dart
1import 'package:firebase_auth/firebase_auth.dart';
2 
3class AuthService {
4 final FirebaseAuth _auth = FirebaseAuth.instance;
5 
6 // Mevcut kullanici stream'i
7 Stream get authStateChanges => _auth.authStateChanges();
8 
9 // Email ile kayit
10 Future signUp({
11 required String email,
12 required String password,
13 }) async {
14 try {
15 final credential = await _auth.createUserWithEmailAndPassword(
16 email: email,
17 password: password,
18 );
19 // Profil guncelle
20 await credential.user?.updateDisplayName(email.split('@').first);
21 return credential;
22 } on FirebaseAuthException catch (e) {
23 throw _handleAuthError(e);
24 }
25 }
26 
27 // Email ile giris
28 Future signIn({
29 required String email,
30 required String password,
31 }) async {
32 try {
33 return await _auth.signInWithEmailAndPassword(
34 email: email,
35 password: password,
36 );
37 } on FirebaseAuthException catch (e) {
38 throw _handleAuthError(e);
39 }
40 }
41 
42 // Google ile giris
43 Future signInWithGoogle() async {
44 final GoogleSignInAccount? googleUser = await GoogleSignIn().signIn();
45 if (googleUser == null) throw Exception('Google sign-in iptal edildi');
46 
47 final GoogleSignInAuthentication googleAuth =
48 await googleUser.authentication;
49 
50 final credential = GoogleAuthProvider.credential(
51 accessToken: googleAuth.accessToken,
52 idToken: googleAuth.idToken,
53 );
54 
55 return _auth.signInWithCredential(credential);
56 }
57 
58 // Cikis yap
59 Future signOut() async {
60 await _auth.signOut();
61 }
62 
63 // Hata yonetimi
64 String _handleAuthError(FirebaseAuthException e) {
65 switch (e.code) {
66 case 'email-already-in-use':
67 return 'Bu email zaten kayitli';
68 case 'invalid-email':
69 return 'Gecersiz email adresi';
70 case 'weak-password':
71 return 'Sifre cok zayif (en az 6 karakter)';
72 case 'user-not-found':
73 return 'Kullanici bulunamadi';
74 case 'wrong-password':
75 return 'Hatali sifre';
76 default:
77 return 'Bir hata olustu: ${e.message}';
78 }
79 }
80}

Easter Egg

Gizli bir bilgi buldun!

Bu bölümde gizli bir bilgi var. Keşfetmek ister misin?


3. Cloud Firestore

Firestore, gercek zamanli NoSQL veritabanidir. Belge (document) ve koleksiyon (collection) yapisinda calisir:

dart
1import 'package:cloud_firestore/cloud_firestore.dart';
2 
3class ProductRepository {
4 final FirebaseFirestore _firestore = FirebaseFirestore.instance;
5 late final CollectionReference> _collection;
6 
7 ProductRepository() {
8 _collection = _firestore.collection('products');
9 }
10 
11 // Urun ekle
12 Future addProduct(Product product) async {
13 final doc = await _collection.add(product.toMap());
14 return doc.id;
15 }
16 
17 // Urun guncelle
18 Future updateProduct(String id, Map data) async {
19 await _collection.doc(id).update(data);
20 }
21 
22 // Urun sil
23 Future deleteProduct(String id) async {
24 await _collection.doc(id).delete();
25 }
26 
27 // Tekil urun getir
28 Future getProduct(String id) async {
29 final doc = await _collection.doc(id).get();
30 if (!doc.exists) return null;
31 return Product.fromMap(doc.data()!, doc.id);
32 }
33 
34 // Gercek zamanli liste dinle
35 Stream> watchProducts({
36 String? category,
37 int limit = 20,
38 }) {
39 Query> query = _collection;
40 
41 if (category != null) {
42 query = query.where('category', isEqualTo: category);
43 }
44 
45 return query
46 .orderBy('createdAt', descending: true)
47 .limit(limit)
48 .snapshots()
49 .map((snapshot) {
50 return snapshot.docs
51 .map((doc) => Product.fromMap(doc.data(), doc.id))
52 .toList();
53 });
54 }
55 
56 // Sayfalama ile listeleme
57 Future> getProductsPaginated({
58 DocumentSnapshot? lastDocument,
59 int pageSize = 10,
60 }) async {
61 Query> query = _collection
62 .orderBy('createdAt', descending: true)
63 .limit(pageSize);
64 
65 if (lastDocument != null) {
66 query = query.startAfterDocument(lastDocument);
67 }
68 
69 final snapshot = await query.get();
70 return snapshot.docs
71 .map((doc) => Product.fromMap(doc.data(), doc.id))
72 .toList();
73 }
74 
75 // Toplu islem (batch write)
76 Future batchUpdatePrices(Map priceUpdates) async {
77 final batch = _firestore.batch();
78 
79 for (final entry in priceUpdates.entries) {
80 batch.update(
81 _collection.doc(entry.key),
82 {'price': entry.value, 'updatedAt': FieldValue.serverTimestamp()},
83 );
84 }
85 
86 await batch.commit();
87 }
88}

4. Cloud Storage

dart
1import 'package:firebase_storage/firebase_storage.dart';
2import 'dart:io';
3 
4class StorageService {
5 final FirebaseStorage _storage = FirebaseStorage.instance;
6 
7 // Dosya yukle (progress ile)
8 Future uploadFile({
9 required File file,
10 required String path,
11 void Function(double)? onProgress,
12 }) async {
13 final ref = _storage.ref(path);
14 final uploadTask = ref.putFile(file);
15 
16 uploadTask.snapshotEvents.listen((event) {
17 final progress = event.bytesTransferred / event.totalBytes;
18 onProgress?.call(progress);
19 });
20 
21 await uploadTask;
22 return ref.getDownloadURL();
23 }
24 
25 // Resim yukle (boyut sinirlamasi ile)
26 Future uploadImage({
27 required File imageFile,
28 required String userId,
29 int maxSizeBytes = 5 * 1024 * 1024, // 5MB
30 }) async {
31 final fileSize = await imageFile.length();
32 if (fileSize > maxSizeBytes) {
33 throw Exception('Dosya boyutu cok buyuk (maks 5MB)');
34 }
35 
36 final fileName = DateTime.now().millisecondsSinceEpoch.toString();
37 final path = 'users/$userId/images/$fileName.jpg';
38 
39 return uploadFile(file: imageFile, path: path);
40 }
41 
42 // Dosya sil
43 Future deleteFile(String path) async {
44 await _storage.ref(path).delete();
45 }
46}

5. Cloud Functions

Sunucu tarafli islemler icin Cloud Functions kullanilir:

dart
1import 'package:cloud_functions/cloud_functions.dart';
2 
3class FunctionsService {
4 final FirebaseFunctions _functions = FirebaseFunctions.instance;
5 
6 // Callable function cagir
7 Future> callFunction(
8 String name,
9 Map data,
10 ) async {
11 try {
12 final result = await _functions.httpsCallable(name).call(data);
13 return Map.from(result.data as Map);
14 } on FirebaseFunctionsException catch (e) {
15 throw Exception('Cloud Function hatasi: ${e.message}');
16 }
17 }
18 
19 // Ornek: Odeme islemi baslat
20 Future createPaymentIntent(double amount, String currency) async {
21 final result = await callFunction('createPaymentIntent', {
22 'amount': (amount * 100).toInt(),
23 'currency': currency,
24 });
25 return result['clientSecret'] as String;
26 }
27}

6. Firebase Analytics

dart
1import 'package:firebase_analytics/firebase_analytics.dart';
2 
3class AnalyticsService {
4 final FirebaseAnalytics _analytics = FirebaseAnalytics.instance;
5 
6 // Sayfa goruntulenme
7 Future logScreenView(String screenName) async {
8 await _analytics.logScreenView(screenName: screenName);
9 }
10 
11 // Ozel event
12 Future logEvent(String name, Map params) async {
13 await _analytics.logEvent(name: name, parameters: params);
14 }
15 
16 // Satin alma
17 Future logPurchase(double value, String currency) async {
18 await _analytics.logPurchase(value: value, currency: currency);
19 }
20 
21 // Kullanici ozelligi
22 Future setUserProperty(String name, String value) async {
23 await _analytics.setUserProperty(name: name, value: value);
24 }
25}

7. Crashlytics

dart
1import 'package:firebase_crashlytics/firebase_crashlytics.dart';
2 
3class CrashlyticsService {
4 final FirebaseCrashlytics _crashlytics = FirebaseCrashlytics.instance;
5 
6 // Kullanici bilgisi ekle
7 Future setUser(String userId) async {
8 await _crashlytics.setUserIdentifier(userId);
9 }
10 
11 // Non-fatal hata raporla
12 Future reportError(dynamic error, StackTrace stack) async {
13 await _crashlytics.recordError(error, stack);
14 }
15 
16 // Ozel anahtar ekle
17 Future setCustomKey(String key, String value) async {
18 await _crashlytics.setCustomKey(key, value);
19 }
20 
21 // Log mesaji ekle (crash raporunda gorunur)
22 Future log(String message) async {
23 await _crashlytics.log(message);
24 }
25}

8. Remote Config

dart
1import 'package:firebase_remote_config/firebase_remote_config.dart';
2 
3class RemoteConfigService {
4 final FirebaseRemoteConfig _config = FirebaseRemoteConfig.instance;
5 
6 Future initialize() async {
7 await _config.setConfigSettings(RemoteConfigSettings(
8 fetchTimeout: const Duration(minutes: 1),
9 minimumFetchInterval: const Duration(hours: 1),
10 ));
11 
12 await _config.setDefaults({
13 'feature_new_ui': false,
14 'max_upload_size_mb': 5,
15 'maintenance_mode': false,
16 'welcome_message': 'Hosgeldiniz!',
17 });
18 
19 await _config.fetchAndActivate();
20 }
21 
22 bool getBool(String key) => _config.getBool(key);
23 int getInt(String key) => _config.getInt(key);
24 String getString(String key) => _config.getString(key);
25}

9. Guvenlik Kurallari

Firebase guvenlik kurallari kritiktir. Yanlis kurallar veri ihlallerine yol acar:

Firestore Kurallari

Kural
Aciklama
Risk
**allow read, write: if true**
Herkese acik
KRITIK - ASLA production'da kullanma
**allow read: if request.auth != null**
Giris yapmis kullanicilar
ORTA - kendi verisini gormeli
**allow write: if request.auth.uid == resource.data.userId**
Sadece sahip
DUSUK - dogru yaklasim
**allow read: if get(path).data.role == 'admin'**
Rol bazli
DUSUK - en guvenli

10. Best Practices

  • Offline desteigi: her zaman aktif edin: Firestore varsayilan olarak offline cache saglar
  • Index: olusturmayi unutmayin: Karmasik sorgularda Firestore index gerektirir
  • Batch write: kullanin: 500'e kadar islemi tek seferde yapin
  • Security Rules: test edin: Firebase emulator ile kurallari test edin
  • Analytics: ile kullnici davranisini takip edin
  • Crashlytics: ile hatalari gercek zamanli izleyin

Sonuc ve Oneriler

Firebase, Flutter ile birlestiginde inanilmaz guclu bir platform olusturuyor. Authentication, veritabani, depolama, analytics ve hata raporlama — hepsi tek bir SDK ile erisimde.

ALTIN İPUCU

Bu yazının en değerli bilgisi

Bu ipucu, yazının en önemli çıkarımını içeriyor.

Okuyucu Ödülü

Tebrikler! Bu yazıyı sonuna kadar okuduğun için sana özel bir hediyem var:

Etiketler

#Flutter#Firebase#Firestore#Authentication#Cloud Functions#Dart
Muhittin Çamdalı

Muhittin Çamdalı

Senior iOS Developer

12+ yıllık deneyime sahip iOS Developer. Swift, SwiftUI ve modern iOS mimarileri konusunda uzman. Apple platformlarında performanslı ve kullanıcı dostu uygulamalar geliştiriyorum.

iOS Geliştirme Haberleri

Haftalık Swift tips, SwiftUI tricks ve iOS best practices. Spam yok, sadece değerli içerik.

Gizliliğinize saygı duyuyoruz. İstediğiniz zaman abonelikten çıkabilirsiniz.

Paylaş

Bunu da begenebilirsiniz