QueryClient
The QueryClient is the core controller of Fasq. It manages the query cache, deduplication, and garbage collection.
Initialization
Section titled “Initialization”It is best to provide the QueryClient at the top of your widget tree using QueryClientProvider, but it can also be used as a singleton if desired.
import 'package:fasq/fasq.dart';
void main() { final client = QueryClient();
runApp( QueryClientProvider( client: client, child: MyApp(), ), );}Global Configuration
Section titled “Global Configuration”You can define default behaviors for all queries in your app.
final client = QueryClient( config: const CacheConfig( defaultStaleTime: Duration(minutes: 5), // Data is fresh for 5 mins defaultCacheTime: Duration(minutes: 30), // Inactive data kept for 30 mins ),);Cache Management
Section titled “Cache Management”Invalidation
Section titled “Invalidation”Mark data as stale so it gets refetched the next time it’s used.
// Invalidate a single queryclient.invalidateQuery('todos'.toQueryKey());
// Invalidate with refetch (default behavior for active queries)client.invalidateQuery('todos'.toQueryKey(), refetchType: InvalidateType.active);Pre-fetching
Section titled “Pre-fetching”Load data before the user navigates there to provide an instant experience.
await client.prefetchQuery( 'todos'.toQueryKey(), () => fetchTodos(),);Manual Updates
Section titled “Manual Updates”You can update the cache directly without hitting the network (useful for optimistic updates).
// Update dataclient.setQueryData<List<Todo>>( 'todos'.toQueryKey(), (oldData) => [...?oldData, newTodo],);
// Read datafinal todos = client.getQueryData<List<Todo>>('todos'.toQueryKey());Observers
Section titled “Observers”QueryClient supports observers that can monitor all query and mutation lifecycle events. This is useful for logging, analytics, error tracking, and more.
Adding Observers
Section titled “Adding Observers”final client = QueryClient();
// Add built-in loggerclient.addObserver(FasqLogger());
// Add custom observerclient.addObserver(MyCustomObserver());Built-in Logger
Section titled “Built-in Logger”Fasq includes FasqLogger for development debugging:
client.addObserver(FasqLogger( enabled: true, showData: false, // Privacy-first: don't log data by default truncateLength: 100,));For complete logging documentation, see Logging.
Custom Observers
Section titled “Custom Observers”Create custom observers by implementing QueryClientObserver:
class AnalyticsObserver implements QueryClientObserver { @override void onQuerySuccess(QuerySnapshot snapshot, QueryMeta? meta, BuildContext? context) { analytics.track('query_success', { 'key': snapshot.queryKey.toString(), 'duration': calculateDuration(snapshot), }); }
// Implement other observer methods...}Observer Management
Section titled “Observer Management”// Add observerclient.addObserver(myObserver);
// Remove observerclient.removeObserver(myObserver);
// Clear all observersclient.clearObservers();Error Reporters
Section titled “Error Reporters”QueryClient supports error reporters that receive detailed context when queries fail. This is useful for integrating with external error tracking services like Sentry or Crashlytics.
Adding Error Reporters
Section titled “Adding Error Reporters”final client = QueryClient();
// Add error reporterclient.addErrorReporter(SentryErrorReporter());
// You can add multiple reportersclient.addErrorReporter(CrashlyticsErrorReporter());client.addErrorReporter(CustomErrorReporter());Error Reporter Interface
Section titled “Error Reporter Interface”Implement the FasqErrorReporter interface to create custom reporters:
class SentryErrorReporter implements FasqErrorReporter { @override void report(FasqErrorContext context) { Sentry.captureException( context.error, stackTrace: context.stackTrace, hint: Hint.withMap({ 'queryKey': context.queryKey.join('/'), 'retryCount': context.retryCount, 'networkStatus': context.networkStatus ? 'online' : 'offline', }), ); }}Error Context
Section titled “Error Context”When a query fails, reporters receive a FasqErrorContext containing:
- Query key that failed
- Retry count
- Network status
- Error and stack trace
- Sanitized query options (PII automatically removed)
Managing Reporters
Section titled “Managing Reporters”// Add reporterclient.addErrorReporter(myReporter);
// Remove reporterclient.removeErrorReporter(myReporter);For complete documentation on error tracking, including PII sanitization, integration examples, and best practices, see Error Tracking.
Performance Metrics
Section titled “Performance Metrics”Fasq provides built-in performance monitoring to help you understand your app’s query behavior and optimize performance.
Getting Global Metrics
Section titled “Getting Global Metrics”Get a comprehensive snapshot of all performance metrics:
final client = QueryClient();final snapshot = client.getMetrics();
print('Cache hit rate: ${snapshot.cacheMetrics.hitRate}');print('Active queries: ${snapshot.activeQueries}');print('Memory usage: ${snapshot.memoryUsageBytes / 1024 / 1024} MB');Getting Query-Specific Metrics
Section titled “Getting Query-Specific Metrics”Get detailed metrics for a specific query:
final metrics = client.getQueryMetrics('todos'.toQueryKey());
if (metrics != null) { print('Fetch count: ${metrics.fetchCount}'); print('Avg fetch time: ${metrics.averageFetchTime?.inMilliseconds}ms'); print('Throughput: ${metrics.throughputMetrics?.requestsPerMinute} RPM');}Configuring Metrics Exporters
Section titled “Configuring Metrics Exporters”Export metrics to external monitoring systems (console, JSON, OpenTelemetry):
final client = QueryClient();
client.configureMetricsExporters( MetricsConfig( exporters: [ ConsoleExporter(), JsonExporter(), ], exportInterval: Duration(minutes: 1), enableAutoExport: true, ),);For more details, see the Performance Monitoring and Metrics Exporters documentation.
API Reference
Section titled “API Reference”| Method | Description |
|---|---|
fetchQuery | Fetches a query and returns the result (throws on error). |
prefetchQuery | Fetches a query and stores it in cache (no return, safe). |
getQueryData | Synchronously returns the current data in cache. |
setQueryData | Synchronously updates the data in cache. |
invalidateQuery | Marks queries as stale and potentially refetches them. |
cancelQuery | Cancels any outgoing fetches for a query. |
resetQuery | Resets a query to its initial state. |
addObserver | Adds a QueryClientObserver to monitor query/mutation events. |
removeObserver | Removes an observer from the client. |
clearObservers | Removes all observers from the client. |
addErrorReporter | Adds an error reporter to receive query failure notifications. |
removeErrorReporter | Removes an error reporter from the client. |
getMetrics | Returns a snapshot of global performance metrics. |
getQueryMetrics | Returns performance metrics for a specific query. |
configureMetricsExporters | Configures metrics exporters and auto-export. |
exportMetricsManually | Manually triggers an immediate metrics export. |