Poorgramer-Zack/dart-expert-skills / skills/firebase
integrating-firebase
VerifiedFirebase integration for Flutter including Auth, Firestore, FCM, Cloud Storage, Analytics, and Crashlytics. Use when implementing serverless backend features, real-time sync, or push notifications.
| File | Kind | Size |
|---|---|---|
| SKILL.md | skill md | 3.0 KB |
| references/analytics-crashlytics.md | markdown | 3.0 KB |
| references/app-check.md | markdown | 2.9 KB |
| references/auth.md | markdown | 6.2 KB |
| references/cost.md | markdown | 4.2 KB |
| references/database.md | markdown | 3.5 KB |
| references/messaging.md | markdown | 4.2 KB |
| references/serverpod-bff.md | markdown | 4.3 KB |
| references/setup.md | markdown | 2.7 KB |
| references/storage.md | markdown | 2.8 KB |
references/database.md
View on GitHub---
metadata:
last_modified: "2026-03-12 11:18:17 (GMT+8)"
---
# 04 - Firebase Databases (`cloud_firestore`, `firebase_database`)
## Goal
Interact securely and predictably with Firebase's database solutions. This chapter focuses primarily on Cloud Firestore (NoSQL Document Store) and provides brief guidance on the Realtime Database (JSON Tree).
## Instructions
### 1. Cloud Firestore: The `.withConverter` Mandate (CRITICAL)
Firestore inherently returns `Map<String, dynamic>`. If you interact with raw Maps throughout your app, you will inevitably introduce runtime string-typo crashes.
**Rule:** You MUST bind a strictly typed Dart Model (e.g., generated by Freezed) to your Firestore Collections upon declaration.
```dart
// Assume a `UserProfile` model exists with `fromJson` and `toJson`.
final usersCollection = FirebaseFirestore.instance.collection('users').withConverter<UserProfile>(
fromFirestore: (snapshot, _) => UserProfile.fromJson(snapshot.data()!),
toFirestore: (user, _) => user.toJson(),
);
// Now, reading is 100% type-safe
Future<List<UserProfile>> fetchActiveUsers() async {
final querySnapshot = await usersCollection.where('isActive', isEqualTo: true).get();
// No manual Map casting needed!
return querySnapshot.docs.map((doc) => doc.data()).toList();
}
// Writing is 100% type-safe
Future<void> addUser(UserProfile newUser) async {
// `add` expects a UserProfile, NOT a Map
await usersCollection.add(newUser);
}
```
### 2. Firestore Document IDs
Often, you need the unique Document ID generated by Firestore attached to your Model. Do not store the `id` inside the document map itself unless strictly necessary. Instead, inject it during the `fromFirestore` conversion.
```dart
final postsCollection = FirebaseFirestore.instance.collection('posts').withConverter<Post>(
fromFirestore: (snapshot, _) {
final data = snapshot.data()!;
// Assuming `Post` has an `id` field, inject it post-fetch:
return Post.fromJson({...data, 'id': snapshot.id});
},
toFirestore: (post, _) {
final data = post.toJson();
data.remove('id'); // Ensure 'id' isn't explicitly written as a redundant field
return data;
},
);
```
### 3. Firestore Sub-collections vs Root Collections
* **Sub-collections (`users/123/posts/456`)**: Use these when data is strictly owned by the parent document and you rarely need to query across multiple parents.
* **Root Collections (`posts` with a `userId` field)**: Use this if you need "Collection Group Queries" (e.g., fetching all posts across all users sorted by date). This is generally the more scalable NoSQL pattern.
### 4. Firebase Realtime Database (RTDB)
Use RTDB (`firebase_database`) primarily for presence systems (e.g., "User is Online"), hyper-fast ephemeral data (like cursor positions in a multiplayer game), or extremely deep JSON queries. For 95% of standard app data, use Firestore.
```dart
final DatabaseReference rtdbRef = FirebaseDatabase.instance.ref("users/123");
// Read once
final DataSnapshot snapshot = await rtdbRef.get();
if (snapshot.exists) {
print(snapshot.value);
}
// Write
await rtdbRef.set({
"name": "John Doe",
"status": "online"
});
```
## Constraints
* **No Unbounded Queries:** Never execute `.get()` on an enormous collection without a `.limit()`. Fetching 10,000 documents inadvertently will cost you 10,000 document reads instantly on your Firebase bill.
* **Batch Writes:** If you are writing to multiple documents simultaneously, always use `FirebaseFirestore.instance.batch()` to ensure atomicity (all succeed, or all fail together) and reduce API trip latency.
Related skills
| Skill | Stars | Updated | Works with | Status | Install |
|---|---|---|---|---|---|
| deprecation-and-migrationaddyosmani/agent-skillsManages deprecation and migration. Use when removing old systems, APIs, or features. Use when migrating users from one implementation to another. Use when migrating a database schema in production, such as renaming or dropping a column without downtime (expand/contract). Use when deciding whether to maintain or sunset existing code. | Stars: 119k | Updated | Claude CodeCodex | Verified | Install |
| performance-optimizationaddyosmani/agent-skillsOptimizes application performance across frontend, backend, queries, and databases. Use when performance requirements exist, when you suspect performance regressions, when Core Web Vitals or load times need improvement, when N+1 query patterns need fixing, or when profiling reveals bottlenecks. | Stars: 119k | Updated | Claude CodeCodex | Verified | Install |
| agent-cost-reportthedotmack/claude-memBelievable agent cost report for any period, default the last 7 full days PT, not counting today. Measured tokens from Claude Code transcripts priced at OpenRouter list prices (ESTIMATED), measured provider spend when a sanctioned source exists, note-taker cost separate, Timing-style HTML/PDF plus report.json, line-items.csv, evidence.json. | Stars: 118k | Updated | Claude CodeCodex | Verified | Install |
| agent-cost-reportthedotmack/claude-memBelievable agent cost report for any period, default the last 7 full days PT, not counting today. Measured tokens from Claude Code transcripts priced at OpenRouter list prices (ESTIMATED), measured provider spend when a sanctioned source exists, note-taker cost separate, Timing-style HTML/PDF plus report.json, line-items.csv, evidence.json. | Stars: 118k | Updated | Claude CodeCodex | Verified | Install |