ฐานข้อมูล Cloud Firestore
ใช้ Cloud Firestore ซึ่งเป็นฐานข้อมูลเอกสาร NoSQL เพื่อจัดเก็บและซิงค์ข้อมูลแบบเรียลไทม์ระหว่างไคลเอ็นต์ที่เชื่อมต่อทั้งหมด
ฐานข้อมูล Cloud Firestore เป็นบทเรียน Flutter Mobile Development ฟรีบน CoddyKit นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน Flutter Mobile Development และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส Flutter Mobile Development มีบทเรียนทั้งหมด 4 บทเรียน
บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ
What is Cloud Firestore?
Welcome to Cloud Firestore! It's a flexible, scalable NoSQL document database for mobile, web, and server development from Firebase.
It keeps your data in sync across client apps in real-time and offers offline support, making it great for responsive apps.
How Data is Organized
Firestore stores data in documents, which are like JSON objects. Documents are organized into collections, which are containers for documents.
- Collections: Groups of documents.
- Documents: Key-value pairs (fields) that can contain subcollections.
- Fields: The actual data points within a document.
Firestore vs. Realtime Database
Firebase offers two databases: Firestore and Realtime Database. Firestore is generally preferred for new apps due to its more intuitive data model, powerful querying, and better scalability.
Think of Firestore as a modern upgrade, offering better structure and query capabilities for complex data.
Accessing Firestore in Flutter
To interact with Firestore, first ensure you've initialized Firebase (from Lesson 1). Then, get an instance of FirebaseFirestore:
You'll need to add the cloud_firestore package to your pubspec.yaml.
import 'package:cloud_firestore/cloud_firestore.dart';
// Ensure Firebase is initialized in your main() or similar
// For example: await Firebase.initializeApp();
void main() {
FirebaseFirestore db = FirebaseFirestore.instance;
print("Firestore instance obtained!");
// You would typically use this 'db' instance
// within your Flutter widgets.
}Storing New Documents
You can add data to Firestore using set() or add(). set() lets you specify the document ID, while add() auto-generates one.
Let's add a new user to a 'users' collection:
import 'package:cloud_firestore/cloud_firestore.dart';
// Assume Firebase.initializeApp() is done.
void main() async {
FirebaseFirestore db = FirebaseFirestore.instance;
// Using .add() - Firestore generates a document ID
DocumentReference docRef = await db.collection("users").add({
"name": "Alice",
"email": "alice@example.com",
"age": 30,
"isActive": true
});
print("Document added with ID: ${docRef.id}");
// Using .set() - you provide the document ID
await db.collection("cities").doc("LA").set({
"name": "Los Angeles",
"state": "CA",
"country": "USA"
});
print("City 'LA' added.");
}Fetching Data Once
To read a single document, you reference its collection and ID, then call get().
This fetches the data once. We'll look at real-time updates next.
import 'package:cloud_firestore/cloud_firestore.dart';
// Assume Firebase.initializeApp() is done.
void main() async {
FirebaseFirestore db = FirebaseFirestore.instance;
// Replace 'some_doc_id' with an actual ID from your Firestore
DocumentSnapshot doc = await db.collection("users").doc("some_doc_id").get();
if (doc.exists) {
print("Document data: ${doc.data()}");
print("User name: ${doc.get('name')}");
} else {
print("No such document!");
}
}Modifying Existing Documents
Use the update() method on a document reference to change specific fields without overwriting the entire document.
This is useful for making small adjustments to existing records.
import 'package:cloud_firestore/cloud_firestore.dart';
// Assume Firebase.initializeApp() is done.
void main() async {
FirebaseFirestore db = FirebaseFirestore.instance;
// Replace 'some_doc_id' with an actual ID
String docIdToUpdate = "some_doc_id";
await db.collection("users").doc(docIdToUpdate).update({
"age": 31,
"city": "New York" // Add a new field
});
print("Document updated successfully!");
// You can also update nested fields using dot notation
// await db.collection("users").doc(docIdToUpdate).update({
// "address.street": "Main St"
// });
}Removing Documents and Fields
You can delete an entire document or just specific fields within a document.
- Use
delete()on a document reference to remove the whole document. - Use
FieldValue.delete()in anupdate()call to remove a specific field.
import 'package:cloud_firestore/cloud_firestore.dart';
// Assume Firebase.initializeApp() is done.
void main() async {
FirebaseFirestore db = FirebaseFirestore.instance;
// Replace with an actual document ID you wish to delete
String docIdToDelete = "some_other_doc_id";
// Delete a specific field from a document
await db.collection("users").doc("some_doc_id").update({
"isActive": FieldValue.delete()
});
print("Field 'isActive' deleted from document 'some_doc_id'.");
// Delete an entire document
await db.collection("users").doc(docIdToDelete).delete();
print("Document '${docIdToDelete}' deleted.");
}Real-time Data Updates
One of Firestore's most powerful features is real-time data synchronization. Use snapshots() to listen for changes to a document or collection.
Your app will automatically receive updates whenever the data changes in the database.
import 'package:cloud_firestore/cloud_firestore.dart';
// Assume Firebase.initializeApp() is done.
void main() {
FirebaseFirestore db = FirebaseFirestore.instance;
// Listen to a single document
db.collection("users").doc("some_doc_id").snapshots().listen((snapshot) {
if (snapshot.exists) {
print("Real-time update for doc: ${snapshot.data()}");
} else {
print("Document no longer exists.");
}
});
// Listen to a whole collection
db.collection("users").snapshots().listen((snapshot) {
print("Real-time update for collection. Total docs: ${snapshot.docs.length}");
for (var doc in snapshot.docs) {
print(" - ${doc.id}: ${doc.data()['name']}");
}
});
print("Listeners set up. App will now receive real-time updates.");
// In a real Flutter app, this would be part of a StatefulWidget's initState
// and listeners would be cancelled in dispose().
}Advanced Data Queries
Firestore allows powerful queries to filter and order your data. You can chain multiple where() clauses and orderBy() calls.
where('field', isEqualTo: value)orderBy('field', descending: true)limit(count)
Remember, complex queries might require creating indexes in the Firebase console.
Firestore Operations Check
Which of the following statements about Cloud Firestore operations are TRUE?
Firestore Summary
Great job! You've learned the fundamentals of Cloud Firestore, including its NoSQL structure, how to add, read, update, and delete data.
We also explored real-time listeners and basic querying. Firestore is a powerful tool for building dynamic, data-driven Flutter apps!
Next, we'll explore Firebase Cloud Storage for handling larger files like images and videos.
คำถามที่พบบ่อย
บทเรียน “ฐานข้อมูล Cloud Firestore” ฟรีหรือไม่
ใช่ — ข้อความเต็มของ “ฐานข้อมูล Cloud Firestore” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส Flutter Mobile Development ให้อัปเกรดเป็น CoddyKit PRO คอร์ส Flutter Mobile Development มีบทเรียนทั้งหมด 4 บทเรียน
คุณจะเรียนรู้อะไรในบทเรียน “ฐานข้อมูล Cloud Firestore”
ใช้ Cloud Firestore ซึ่งเป็นฐานข้อมูลเอกสาร NoSQL เพื่อจัดเก็บและซิงค์ข้อมูลแบบเรียลไทม์ระหว่างไคลเอ็นต์ที่เชื่อมต่อทั้งหมด คุณปฏิบัติ Flutter Mobile Development ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน
คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน Flutter Mobile Development หรือไม่
ไม่จำเป็นต้องมีประสบการณ์มาก่อน Flutter Mobile Development บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน
บทเรียน “ฐานข้อมูล Cloud Firestore” ใช้เวลานานแค่ไหน
บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย
ฉันเขียนและรันโค้ดในบทเรียน Flutter Mobile Development นี้ได้ไหม
ได้ บทเรียน Flutter Mobile Development ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ
บทเรียนทั้งหมดในหลักสูตรนี้
- การตั้งค่า Firebase และการยืนยันตัวตน
- ฐานข้อมูล Cloud Firestore
- Cloud Storage และฟังก์ชัน
- การส่งข้อความบนคลาวด์ของ Firebase และการแจ้งเตือน