subCollection<U> method

FirestorePlus<U> subCollection<U>({
  1. required String subPath,
  2. required String? itemUid,
  3. required U tConstructor(
    1. Map<String, dynamic>
    ),
})

Creates a FirestorePlus instance for a sub-collection.

This method allows you to work with sub-collections in a type-safe manner. Sub-collections are nested collections within documents.

Usage

// Create a user instance
final userPlus = FirestorePlus<User>.instance(
  tConstructor: User.withMap,
  path: 'users',
  uid: 'user123',
);

// Access user's posts sub-collection
final postsPlus = userPlus.subCollection<Post>(
  subPath: 'posts',
  itemUid: null, // For entire collection
  tConstructor: Post.withMap,
);

// Add a post to user's sub-collection
final post = Post(uid: '', title: 'My Post', content: 'Content here');
await postsPlus.add(object: post);

// Get all posts for a user
final allPosts = await postsPlus.futures;

Parameters

  • subPath: The name of the sub-collection (e.g., 'posts', 'comments')
  • itemUid: Document ID in the sub-collection (null for collection operations)
  • tConstructor: Constructor function for the sub-collection type

When to Use

  • itemUid: null: For collection operations (add, list, search)
  • itemUid: "id": For single document operations (get, update, delete)

Performance Considerations

  • Sub-collections can impact performance with large datasets
  • Consider the depth of nesting (avoid deeply nested sub-collections)
  • Use appropriate indexes for sub-collection queries

Implementation

FirestorePlus<U> subCollection<U>({
  required String subPath,
  required String? itemUid,
  required U Function(Map<String, dynamic>) tConstructor,
}) {
  return FirestorePlus<U>.instance(
    app: app,
    uid: itemUid ?? "none", // For sub-collections, on ne spécifie pas d'uid par défaut
    limit: limit,
    tConstructor: tConstructor,
    path: '$path/$uid/$subPath',
  );
}