TCollectionService<DTO extends TWriteableId, MODEL extends TModel<DTO>> class

A service for managing a collection of Firestore documents with synchronized local state.

The TCollectionService provides a robust foundation for managing collections of documents that need to be synchronized between Firestore and local state. It handles:

  • Local state management with optimistic updates
  • Remote state synchronization
  • Batch operations
  • Transaction support
  • Error handling
  • Automatic user authentication state sync

Type Parameters:

  • DTO - The document type, must extend TWriteableId

Example:

class UserService extends TurboCollectionService<User, UserApi> {
  UserService({required super.api});

  Future<void> updateUserName(String userId, String newName) async {
    final user = findById(userId);
    final updated = user.copyWith(name: newName);
    await updateDoc(doc: updated);
  }
}

Features:

  • Automatic local state updates before remote operations
  • Optimistic UI updates with rollback on failure
  • Batch operations for multiple documents
  • Transaction support for atomic operations
  • Automatic stream update blocking during mutations
  • Error handling and logging
  • User authentication state synchronization
Inheritance
Implementers

Constructors

TCollectionService({required TFirestoreCollection<DTO> collection, required TCollectionModelBuilderDef<DTO, MODEL> modelBuilder, TSortOption? initialSort, Set<TFilterInput<dynamic, TFilterOption, dynamic>>? initialFilters, TModelDocsBuilderDef<DTO, MODEL>? modelDocsBuilder, TCollectionApiBuilderDef<DTO, MODEL>? apiBuilder, TCollectionStreamBuilderDef<DTO, MODEL>? streamBuilder, TCollectionValueBuilderDef<DTO, MODEL>? initialValue, TCollectionValueBuilderDef<DTO, MODEL>? defaultValue, bool initialiseStream = true, IFirestoreCacheService? firestoreCacheService, List<Future> readyDeps(User user)?})
Creates a new TCollectionService instance.

Properties

analytics → TAnalytics
Provides the configured TAnalytics functionality through the Turbolytics mixin per type of D.
latefinalinherited
api TFirestoreApi<DTO>
The Firestore API instance for remote operations.
latefinal
apiBuilder TCollectionApiBuilderDef<DTO, MODEL>?
Optional builder function to create the Firestore API instance. If not provided, the API will be created using the collection's api() method.
final
collection TFirestoreCollection<DTO>
The Firestore collection definition that this service manages.
final
defaultValue TCollectionValueBuilderDef<DTO, MODEL>?
Function to provide default document value.
final
docs ValueListenable<TModelDocs<DTO, MODEL>>
A listenable that provides the current documents indexed by their IDs.
no setter
docsNotifier → TNotifier<TModelDocs<DTO, MODEL>>
Local state for documents, indexed by their IDs.
latefinal
docsPerId ValueListenable<TModelDocs<DTO, MODEL>>
no setter
firestoreCacheService IFirestoreCacheService?
Optional Firestore cache service for caching document data locally.
final
hasDocs bool
Whether the collection has any documents.
no setter
hashCode int
The hash code for this object.
no setterinherited
initialFilters Set<TFilterInput<dynamic, TFilterOption, dynamic>>?
Initial filter of the list inside model docs.
final
initialSort TSortOption?
Initial sort of the list inside model docs.
final
initialValue TCollectionValueBuilderDef<DTO, MODEL>?
Function to provide initial document value.
final
isReady Future<void>
Future that completes when the service is ready to use.
no setter
listenable Listenable
Listenable for the document collection state.
no setter
location String
Used to define the location of Turbolytics logging and implementation.
no setterinherited
log → TLog
Used to provide all logging capabilities.
latefinalinherited
modelBuilder TCollectionModelBuilderDef<DTO, MODEL>
Function to convert Firestore documents into local model instances.
final
modelDocsBuilder TModelDocsBuilderDef<DTO, MODEL>?
Optional builder function to create the local model documents state from a list of DTOs. If not provided, the state will be created using TModelDocs.fromDtos().
final
onAuth FutureOr Function(User user)?
Called when a user is authenticated.
getter/setter pairinherited-setteroverride-getter
onData Future<void> Function(List<DTO>? value, User? user)
Handles data updates from the Firestore stream.
no setteroverride
readyDeps List<Future> Function(User user)?
List of dependencies to wait for before anything else.
final
runtimeType Type
A representation of the runtime type of the object.
no setterinherited
stream Stream<List<DTO>> Function(User user)
Returns a stream of data for the authenticated user.
no setteroverride
streamBuilder TCollectionStreamBuilderDef<DTO, MODEL>?
Optional builder function to create the Firestore stream. If not provided, the stream will be created using the API's streamAllWithConverter() method.
final
user ↔ User?
The currently authenticated Firebase user.
getter/setter pairinherited
userId String?
The ID of the currently authenticated user.
no setterinherited

Methods

analyticsAs<A extends TAnalytics>() → A
Provides the configured TAnalytics functionality through the Turbolytics mixin per type of A.
inherited
clearLocalDocs({bool doNotifyListeners = true}) → void
Clears all documents from local state.
createDoc({Transaction? transaction, required CreateDocDef<DTO, MODEL> doc, bool doNotifyListeners = true}) Future<TurboResponse<DTO>>
Creates a new document both locally and in Firestore.
createDocs({Transaction? transaction, required List<CreateDocDef<DTO, MODEL>> docs, bool doNotifyListeners = true}) Future<TurboResponse<List<DTO>>>
Creates multiple documents both locally and in Firestore.
createLocalDoc({required CreateDocDef<DTO, MODEL> doc, bool doNotifyListeners = true}) → DTO
Creates a new document in local state.
createLocalDocs({required List<CreateDocDef<DTO, MODEL>> docs, bool doNotifyListeners = true}) List<DTO>
Creates multiple new documents in local state.
defaultDocs() TModelDocs<DTO, MODEL>
defaultValues() List<DTO>
deleteDoc({required String id, bool doNotifyListeners = true, Transaction? transaction}) Future<TurboResponse<void>>
Deletes a document both locally and from Firestore.
deleteDocs({Transaction? transaction, required List<String> ids, bool doNotifyListeners = true}) Future<TurboResponse<void>>
Deletes multiple documents both locally and from Firestore.
deleteLocalDoc({required String id, bool doNotifyListeners = true}) → void
Deletes a document from local state.
deleteLocalDocs({required List<String> ids, bool doNotifyListeners = true}) → void
Deletes multiple documents from local state.
dispose() Future<void>
Disposes of the service by cleaning up resources.
override
exists(String id) bool
Whether a document with the given ID exists.
findById(String id) → MODEL
Finds a document by its ID. Throws if not found.
getById({required String id, String? collectionPathOverride, bool tryCache = true, bool forceCacheRefresh = false}) Future<TurboResponse<MODEL>>
getCustomClaim<T>(String key, {T? defaultValue}) → T?
Returns a specific custom claim by key.
inherited
getCustomClaims() Map<String, dynamic>?
Returns all custom claims from the cached token.
inherited
getTokenResult() Future<IdTokenResult?>
Returns the cached token result with claims.
inherited
initialDocs() TModelDocs<DTO, MODEL>
initialValues() List<DTO>?
listAll({bool tryCache = true, bool forceCacheRefresh = false}) Future<TurboResponse<List<MODEL>>>
listByIds(Iterable<String> ids) List<MODEL>
listByQuery({required CollectionReferenceDef<DTO> collectionReferenceQuery, required String whereDescription, bool tryCache = true, bool forceCacheRefresh = false}) Future<TurboResponse<List<MODEL>>>
listBySearchTermWithConverter({required String searchTerm, required String searchField, required TSearchTermType searchTermType, bool doSearchNumberEquivalent = false, int? limit}) Future<TurboResponse<List<MODEL>>>
markAsReady() → void
Marks the service as ready by completing the ready state.
noSuchMethod(Invocation invocation) → dynamic
Invoked when a nonexistent method or property is accessed.
inherited
onDone(int nrOfRetry, int maxNrOfRetry) → void
Called when the stream is done.
inherited
onError(TFirestoreException error) → void
Called when a stream error occurs.
override
rebuild() → void
Forces a rebuild of the local state.
resetAndTryInitialiseStream() Future<void>
Resets and reinitialized the stream.
inherited
resetLocalDocs({bool doNotifyListeners = true}) → void
Resets the local documents to their initial value.
toString() String
A string representation of this object.
inherited
tryFindById(String? id) → MODEL?
Finds a document by its ID. Returns null if not found.
tryHandleFirebaseAuthException<T>({required FirebaseAuthException firebaseAuthException, required TLog log}) → TurboResponse<T>
Handles Firebase Authentication exceptions and converts them to TurboResponse.
inherited
tryInitialiseStream() Future<void>
Initializes the authentication state stream and data synchronization.
inherited
updateDoc({Transaction? transaction, required String id, required UpdateDocDef<DTO, MODEL> doc, TWriteableId remoteUpdateRequestBuilder(DTO doc)?, bool doNotifyListeners = true}) Future<TurboResponse<DTO>>
Updates a document both locally and in Firestore.
updateDocs({Transaction? transaction, required List<String> ids, required UpdateDocDef<DTO, MODEL> doc, bool doNotifyListeners = true}) Future<TurboResponse<List<DTO>>>
Updates multiple documents both locally and in Firestore.
updateLocalDoc({required String id, required UpdateDocDef<DTO, MODEL> doc, bool doNotifyListeners = true}) → DTO
Updates an existing document in local state.
updateLocalDocs({required List<String> ids, required UpdateDocDef<DTO, MODEL> doc, bool doNotifyListeners = true}) List<DTO>
Updates multiple existing documents in local state.
upsertDoc({Transaction? transaction, required String id, required UpsertDocDef<DTO, MODEL> doc, TSerializable remoteUpdateRequestBuilder(DTO doc)?, bool doNotifyListeners = true}) Future<TurboResponse<DTO>>
Upserts (updates or inserts) a document both locally and in Firestore.
upsertDocs({Transaction? transaction, required List<String> ids, required UpsertDocDef<DTO, MODEL> doc, bool doNotifyListeners = true}) Future<TurboResponse<List<DTO>>>
Upserts (updates or inserts) multiple documents both locally and in Firestore.
upsertLocalDoc({required String id, required UpsertDocDef<DTO, MODEL> doc, bool doNotifyListeners = true}) → DTO
Upserts (updates or inserts) a document in local state.
upsertLocalDocs({required List<String> ids, required UpsertDocDef<DTO, MODEL> doc, bool doNotifyListeners = true}) List<DTO>
Upserts (updates or inserts) multiple documents in local state.
upsertResult({required DTO dto, bool doNotifyListeners = true}) → MODEL
upsertResults({required Iterable<DTO> dtos, bool doNotifyListeners = true}) List<MODEL>
vars<V extends TVars>({String? id}) → V
Returns a new instance of V with basic variables filled in.

Operators

operator ==(Object other) bool
The equality operator.
inherited