Chuyển đến nội dung chính

Bài 11: Firebase Integration

Firebase setup với FlutterFire CLI. Cloud Firestore CRUD, realtime listeners. Firebase Auth, Cloud Storage, Cloud Messaging. Analytics, Crashlytics.

💻 Lập trình — Bài 11 Bài 11: Firebase Integration

Flutter & Dart: Từ Cơ bản đến Nâng cao

Phần 3: Networking & Data

xdev.asia

1. Firebase Setup

# Cài FlutterFire CLI
dart pub global activate flutterfire_cli

# Cấu hình project
flutterfire configure --project=my-flutter-app
void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform);
  runApp(const MyApp());
}

2. Cloud Firestore

class FirestoreProductRepository {
  final _collection = FirebaseFirestore.instance.collection('products');

  // Create
  Future<void> add(Product product) async {
    await _collection.doc(product.id).set(product.toJson());
  }

  // Read
  Future<List<Product>> getAll() async {
    final snapshot = await _collection.orderBy('createdAt', descending: true).get();
    return snapshot.docs.map((doc) => Product.fromJson(doc.data())).toList();
  }

  // Realtime stream
  Stream<List<Product>> watchAll() {
    return _collection
        .orderBy('createdAt', descending: true)
        .snapshots()
        .map((snapshot) => snapshot.docs.map((doc) => Product.fromJson(doc.data())).toList());
  }

  // Query
  Future<List<Product>> getByCategory(String category, {int limit = 20}) async {
    final snapshot = await _collection
        .where('category', isEqualTo: category)
        .where('price', isGreaterThan: 0)
        .limit(limit)
        .get();
    return snapshot.docs.map((doc) => Product.fromJson(doc.data())).toList();
  }

  // Update
  Future<void> update(String id, Map<String, dynamic> data) async {
    await _collection.doc(id).update(data);
  }

  // Delete
  Future<void> delete(String id) async {
    await _collection.doc(id).delete();
  }
}

3. Cloud Storage

class StorageService {
  final _storage = FirebaseStorage.instance;

  Future<String> uploadImage(File file, String path) async {
    final ref = _storage.ref().child(path);
    final uploadTask = ref.putFile(file, SettableMetadata(contentType: 'image/jpeg'));

    uploadTask.snapshotEvents.listen((event) {
      final progress = event.bytesTransferred / event.totalBytes;
      debugPrint('Upload: ${(progress * 100).toStringAsFixed(0)}%');
    });

    final snapshot = await uploadTask;
    return snapshot.ref.getDownloadURL();
  }
}

4. Crashlytics & Analytics

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform);

  FlutterError.onError = FirebaseCrashlytics.instance.recordFlutterFatalError;
  PlatformDispatcher.instance.onError = (error, stack) {
    FirebaseCrashlytics.instance.recordError(error, stack, fatal: true);
    return true;
  };

  await FirebaseAnalytics.instance.logEvent(name: 'app_open');
  runApp(const MyApp());
}

Bài tiếp theo: Authentication & Authorization.