Firebase

Backend-as-a-Service (BaaS) โดย Google — ให้บริการ backend สำเร็จรูปไม่ต้องเขียน server เอง ใช้กับ Flutter ได้โดยตรง

บริการที่เรียนในคอร์ส Academind

1. Firebase Realtime Database (Section 12)

ฐานข้อมูล NoSQL แบบ real-time — ข้อมูลอัปเดตทุก client ทันที

import 'package:http/http.dart' as http;
import 'dart:convert';
 
// GET — ดึงข้อมูล
final response = await http.get(
  Uri.https('your-project.firebaseio.com', 'items.json'),
);
final data = json.decode(response.body);
 
// POST — เพิ่มข้อมูล
await http.post(
  Uri.https('your-project.firebaseio.com', 'items.json'),
  headers: {'Content-Type': 'application/json'},
  body: json.encode({'title': 'Milk', 'quantity': 1}),
);
 
// DELETE — ลบข้อมูล
await http.delete(
  Uri.https('your-project.firebaseio.com', 'items/$id.json'),
);

ใช้ผ่าน HTTP requests ตรงๆ (REST API) — ไม่ต้องลง Firebase SDK สำหรับ Realtime DB

2. Firebase Authentication (Section 14)

ระบบ Login/Signup สำเร็จรูป:

import 'package:firebase_auth/firebase_auth.dart';
 
// สมัครสมาชิก
await FirebaseAuth.instance.createUserWithEmailAndPassword(
  email: email, password: password,
);
 
// เข้าสู่ระบบ
await FirebaseAuth.instance.signInWithEmailAndPassword(
  email: email, password: password,
);
 
// เช็คสถานะ login (real-time)
StreamBuilder(
  stream: FirebaseAuth.instance.authStateChanges(),
  builder: (ctx, snapshot) {
    if (snapshot.hasData) return ChatScreen();   // logged in
    return AuthScreen();                          // not logged in
  },
);

3. Cloud Firestore (Section 14)

ฐานข้อมูล NoSQL แบบ document/collection — ทรงพลังกว่า Realtime DB:

import 'package:cloud_firestore/cloud_firestore.dart';
 
// เพิ่มข้อความ
await FirebaseFirestore.instance.collection('chat').add({
  'text': message,
  'createdAt': Timestamp.now(),
  'userId': user.uid,
  'username': userData['username'],
});
 
// อ่าน (real-time ด้วย StreamBuilder)
StreamBuilder(
  stream: FirebaseFirestore.instance
    .collection('chat')
    .orderBy('createdAt', descending: true)
    .snapshots(),
  builder: (ctx, snapshot) {
    if (snapshot.connectionState == ConnectionState.waiting) {
      return const CircularProgressIndicator();
    }
    final docs = snapshot.data!.docs;
    return ListView.builder(
      itemCount: docs.length,
      itemBuilder: (ctx, i) => Text(docs[i]['text']),
    );
  },
);

4. Firebase Storage (Section 14)

อัพโหลดไฟล์ (รูปภาพ, วิดีโอ ฯลฯ) ขึ้น cloud:

import 'package:firebase_storage/firebase_storage.dart';
 
final ref = FirebaseStorage.instance
    .ref().child('user_images').child('${user.uid}.jpg');
await ref.putFile(imageFile);
final imageUrl = await ref.getDownloadURL();

5. Firebase Cloud Messaging — FCM (Section 14)

Push Notifications:

import 'package:firebase_messaging/firebase_messaging.dart';
 
// ขอ permission
await FirebaseMessaging.instance.requestPermission();
 
// รับ token (ส่งไป server เพื่อ target device นี้)
final token = await FirebaseMessaging.instance.getToken();
 
// ฟัง notification ขณะแอปเปิดอยู่
FirebaseMessaging.onMessage.listen((message) {
  print(message.notification?.title);
});

Realtime DB vs Cloud Firestore

Realtime DatabaseCloud Firestore
โครงสร้างJSON treeDocument/Collection
Queryจำกัดทรงพลัง (filter, sort, compound)
ใช้ผ่านREST API (http package)Firebase SDK
เหมาะกับโปรเจกต์ง่ายๆแอปจริงที่ต้อง query ซับซ้อน

Key Points

  • Firebase ให้ backend สำเร็จรูป — Auth, Database, Storage, Push Notifications
  • Realtime DB ใช้ผ่าน HTTP REST API ไม่ต้องลง SDK (Section 12)
  • Firestore ใช้ผ่าน SDK มี real-time listener ด้วย snapshots() + StreamBuilder
  • Auth จัดการ login/signup + เช็คสถานะด้วย authStateChanges() stream
  • FCM ส่ง push notification ไปยัง device ที่ลงทะเบียน token
  • Flutter — framework ที่ใช้ Firebase เป็น backend
  • Dart — async/await สำหรับเรียก Firebase APIs
  • Widgets — StreamBuilder, FutureBuilder สำหรับแสดงข้อมูลจาก Firebase
  • AWS Services Overview — ทางเลือก cloud อื่น