firebase-cloud-firestore

Integrates Cloud Firestore into Flutter apps. Use when setting up Firestore, designing document/collection structure, reading and writing data, working with real-time listeners, designing for scale, or applying security rules.

520 stars

Best use case

firebase-cloud-firestore is best used when you need a repeatable AI agent workflow instead of a one-off prompt. It is especially useful for teams working in multi. Integrates Cloud Firestore into Flutter apps. Use when setting up Firestore, designing document/collection structure, reading and writing data, working with real-time listeners, designing for scale, or applying security rules.

Integrates Cloud Firestore into Flutter apps. Use when setting up Firestore, designing document/collection structure, reading and writing data, working with real-time listeners, designing for scale, or applying security rules.

Users should expect a more consistent workflow output, faster repeated execution, and less time spent rewriting prompts from scratch.

Practical example

Example input

Use the "firebase-cloud-firestore" skill to help with this workflow task. Context: Integrates Cloud Firestore into Flutter apps. Use when setting up Firestore, designing document/collection structure, reading and writing data, working with real-time listeners, designing for scale, or applying security rules.

Example output

A structured workflow result with clearer steps, more consistent formatting, and an output that is easier to reuse in the next run.

When to use this skill

  • Use this skill when you want a reusable workflow rather than writing the same prompt again and again.

When not to use this skill

  • Do not use this when you only need a one-off answer and do not need a reusable workflow.
  • Do not use it if you cannot install or maintain the related files, repository context, or supporting tools.

Installation

Claude Code / Cursor / Codex

$curl -o ~/.claude/skills/firebase-cloud-firestore/SKILL.md --create-dirs "https://raw.githubusercontent.com/evanca/flutter-ai-rules/main/skills/firebase-cloud-firestore/SKILL.md"

Manual Installation

  1. Download SKILL.md from GitHub
  2. Place it in .claude/skills/firebase-cloud-firestore/SKILL.md inside your project
  3. Restart your AI agent — it will auto-discover the skill

How firebase-cloud-firestore Compares

Feature / Agentfirebase-cloud-firestoreStandard Approach
Platform SupportNot specifiedLimited / Varies
Context Awareness High Baseline
Installation ComplexityUnknownN/A

Frequently Asked Questions

What does this skill do?

Integrates Cloud Firestore into Flutter apps. Use when setting up Firestore, designing document/collection structure, reading and writing data, working with real-time listeners, designing for scale, or applying security rules.

Where can I find the source code?

You can find the source code on GitHub using the link provided at the top of the page.

SKILL.md Source

# Firebase Cloud Firestore Skill

This skill defines how to correctly use Cloud Firestore in Flutter applications.

## When to Use

Use this skill when:

* Setting up and configuring Cloud Firestore in a Flutter project.
* Designing document and collection structure.
* Performing read, write, or real-time listener operations.
* Optimizing for scale and avoiding hotspots.
* Applying Firestore security rules.

---

## 1. Database Selection

Choose **Cloud Firestore** when your app needs:
- Rich, hierarchical data models with subcollections.
- Complex queries: chaining filters, combining filtering and sorting on a property.
- Transactions that atomically read and write data from any part of the database.
- High availability (typical uptime 99.999%) or critical-level reliability.
- Scalability.

Use **Realtime Database** instead for simple data models requiring simple lookups and extremely low-latency synchronization (typical response times under 10ms).

---

## 2. Setup and Configuration

```
flutter pub add cloud_firestore
```

```dart
import 'package:cloud_firestore/cloud_firestore.dart';

final db = FirebaseFirestore.instance; // after Firebase.initializeApp()
```

**Location:**
- Select the database location closest to your users and compute resources.
- Use **multi-region** locations for critical apps (maximum availability and durability).
- Use **regional** locations for lower costs and lower write latency for latency-sensitive apps.

**iOS/macOS:** Consider pre-compiled frameworks to improve build times:
```ruby
pod 'FirebaseFirestore',
  :git => 'https://github.com/invertase/firestore-ios-sdk-frameworks.git',
  :tag => 'IOS_SDK_VERSION'
```

---

## 3. Document Structure

- Avoid document IDs `.` and `..` (special meaning in Firestore paths).
- Avoid forward slashes (`/`) in document IDs (path separators).
- **Do not** use monotonically increasing document IDs (e.g., `Customer1`, `Customer2`) — causes write hotspots.
- Use Firestore's **automatic document IDs** when possible:

```dart
db.collection("users").add(user).then((DocumentReference doc) =>
    print('DocumentSnapshot added with ID: ${doc.id}'));
```

- Avoid these characters in field names (require extra escaping): `.` `[` `]` `*` `` ` ``
- Use **subcollections** within documents to organize complex, hierarchical data rather than deeply nested objects.

---

## 4. Indexing

- Set **collection-level index exemptions** to reduce write latency and storage costs.
- Disable Descending & Array indexing for fields that don't need them.
- Exempt string fields with long values that aren't used for querying.
- Exempt fields with sequential values (e.g., timestamps) from indexing if not used in queries — avoids the 500 writes/second index limit.
- Add single-field exemptions for TTL fields.
- Exempt large array or map fields not used in queries — avoids the 40,000 index entries per document limit.
- Firestore queries are indexed by default; query performance is proportional to the result set size, not the dataset size.

---

## 5. Read and Write Operations

- **Always use asynchronous calls** to minimize latency impact:

```dart
await db.collection("users").get().then((event) {
  for (var doc in event.docs) {
    print("${doc.id} => ${doc.data()}");
  }
});
```

- **Do not use offsets for pagination** — use cursors instead to avoid retrieving and being billed for skipped documents.
- Implement **transaction retries** when accessing Firestore directly through REST or RPC APIs.
- For writing a large number of documents, use a **bulk writer** instead of the atomic batch writer.
- Execute independent operations (e.g., a document lookup and a query) **in parallel**, not sequentially.
- Firestore queries are **shallow**: they only return documents in a specific collection or collection group, not subcollection data.
- Be aware of write rate limits: ~1 write per second per document.

---

## 6. Designing for Scale

- Avoid high read or write rates to **lexicographically close documents** (hotspotting).
- Avoid creating new documents with **monotonically increasing fields** (like timestamps) at a very high rate.
- Avoid **deleting documents** in a collection at a high rate.
- **Gradually increase traffic** when writing to the database at a high rate.
- Avoid queries that skip over recently deleted data — use `start_at` to find the correct start point.
- Distribute writes across different document paths to avoid contention.
- Firestore scales automatically to ~1 million concurrent connections and 10,000 writes/second.

---

## 7. Real-time Updates

- **Limit** the number of simultaneous real-time listeners.
- **Detach listeners** when they are no longer needed:

```dart
final subscription = db.collection("users")
    .snapshots()
    .listen((event) {
      // Handle the data
    });

// When no longer needed:
subscription.cancel();
```

- Use **compound queries** to filter data server-side rather than filtering on the client.
- For large collections, use queries to limit the data being listened to — never listen to an entire large collection.
- For presence functionality (online/offline status), implement custom presence solutions as described in Firebase documentation.

---

## 8. Security

- Always use **Firebase Security Rules** to protect Firestore data.
- **Validate user input** before submitting to Firestore to prevent injection attacks.
- Use **transactions** for operations that require atomic updates to multiple documents.
- Implement proper **error handling** for all Firestore operations.
- Never store sensitive information in Firestore without proper access controls.
- Security rules **do not cascade** unless you use a wildcard.
- If a query's results might contain data the user doesn't have access to, **the entire query fails**.

---

## References

- [Cloud Firestore Flutter documentation](https://firebase.google.com/docs/firestore/quickstart?hl=en&authuser=0&platform=flutter)
- [Cloud Firestore best practices](https://firebase.google.com/docs/firestore/best-practices)
- [Cloud Firestore security rules](https://firebase.google.com/docs/firestore/security/get-started)

Related Skills

firebase-storage

520
from evanca/flutter-ai-rules

Integrates Firebase Cloud Storage into Flutter apps. Use when setting up Storage, uploading or downloading files, managing metadata, handling errors, or applying security rules.

firebase-remote-config

520
from evanca/flutter-ai-rules

Integrates Firebase Remote Config into Flutter apps. Use when setting up Remote Config, managing parameter defaults, fetching and activating values, implementing real-time updates, or handling throttling and testing.

firebase-messaging

520
from evanca/flutter-ai-rules

Integrates Firebase Cloud Messaging (FCM) into Flutter apps. Use when setting up push notifications, handling foreground/background messages, managing permissions, working with FCM tokens, or configuring platform-specific notification behavior.

firebase-in-app-messaging

520
from evanca/flutter-ai-rules

Integrates Firebase In-App Messaging into Flutter apps. Use when setting up in-app messaging, triggering or suppressing messages, managing user privacy and opt-in data collection, or testing campaigns.

firebase-database

520
from evanca/flutter-ai-rules

Integrates Firebase Realtime Database into Flutter apps. Use when setting up Realtime Database, structuring JSON data, querying, performing read/write operations, implementing offline capabilities, or applying security rules.

firebase-data-connect

520
from evanca/flutter-ai-rules

Integrates Firebase Data Connect into Flutter apps. Use when setting up Data Connect, designing queries, handling errors, or applying security and performance best practices.

firebase-crashlytics

520
from evanca/flutter-ai-rules

Integrates Firebase Crashlytics into Flutter apps. Use when setting up crash reporting, handling fatal and non-fatal errors, customizing crash reports with keys/logs/user identifiers, or configuring opt-in reporting.

firebase-cloud-functions

520
from evanca/flutter-ai-rules

Calls Firebase Cloud Functions from Flutter apps. Use when setting up callable functions, passing data to functions, handling errors from function calls, optimizing performance, or testing with the Firebase Emulator Suite.

firebase-auth

520
from evanca/flutter-ai-rules

Integrates Firebase Authentication into Flutter apps. Use when setting up auth, managing auth state, implementing email/password or social sign-in, handling auth errors, managing users, or applying security best practices.

firebase-app-check

520
from evanca/flutter-ai-rules

Integrates Firebase App Check into Flutter apps. Use when setting up App Check, selecting providers per platform, using debug providers during development, enabling enforcement, or applying App Check security best practices.

firebase-analytics

520
from evanca/flutter-ai-rules

Integrates Firebase Analytics into Flutter apps. Use when setting up analytics, logging events, setting user properties, or configuring event parameters.

firebase-ai

520
from evanca/flutter-ai-rules

Integrates Firebase AI Logic into Flutter apps. Use when setting up the firebase_ai plugin, calling Gemini models, handling AI service errors, or applying security and privacy considerations for AI features.