Getting Started
Welcome to fquery — the asynchronous state management and caching library for Flutter and Dart.
Installation
Add fquery to your Flutter project:
flutter pub add fqueryOr add it directly to your pubspec.yaml:
dependencies:
fquery: ^3.1.0Version Compatibility (fquery_core)
fquery re-exports fquery_core directly, so you only need import 'package:fquery/fquery.dart';. If you are using an older version (fquery <= 3.1.0), also add fquery_core to your pubspec.yaml and import package:fquery_core/fquery_core.dart.
TIP
If you love using Flutter Hooks, install flutter_hooks alongside fquery for the ergonomic useQuery and useMutation hooks! If you prefer standard declarative widgets, fquery provides QueryBuilder, MutationBuilder, and InfiniteQueryBuilder out of the box with no extra dependencies.
1. Quickstart (Flutter)
Step 1: Wrap your App with CacheProvider
Place CacheProvider at the root of your widget tree to provide the cache down the hierarchy:
import 'package:flutter/material.dart';
import 'package:fquery/fquery.dart';
// Create a QueryCache instance
final queryCache = QueryCache();
void main() {
runApp(
CacheProvider(
cache: queryCache,
child: const MyApp(),
),
);
}Step 2: Fetch and Observe Data
Using QueryBuilder
Wrap your UI in a QueryBuilder with your query key and fetcher function:
import 'package:flutter/material.dart';
import 'package:fquery/fquery.dart';
class PostsPage extends StatelessWidget {
const PostsPage({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Posts')),
body: QueryBuilder<List<Post>, Exception>(
options: QueryOptions(
queryKey: QueryKey(['posts']),
queryFn: fetchPosts,
staleDuration: const Duration(seconds: 30),
),
builder: (context, posts) {
if (posts.isLoading) {
return const Center(child: CircularProgressIndicator());
}
if (posts.isError) {
return Center(child: Text('Error: ${posts.error}'));
}
return ListView.builder(
itemCount: posts.data!.length,
itemBuilder: (context, index) => ListTile(
title: Text(posts.data![index].title),
),
);
},
),
);
}
}Using Flutter Hooks (useQuery)
If you use flutter_hooks, you can fetch and observe queries using useQuery:
import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:fquery/fquery.dart';
class PostsPage extends HookWidget {
const PostsPage({super.key});
@override
Widget build(BuildContext context) {
// Automatically fetches, caches, deduplicates, and manages state
final posts = useQuery<List<Post>, Exception>(
['posts'],
fetchPosts,
staleDuration: const Duration(seconds: 30),
);
if (posts.isLoading) {
return const Center(child: CircularProgressIndicator());
}
if (posts.isError) {
return Center(child: Text('Error: ${posts.error}'));
}
return ListView.builder(
itemCount: posts.data!.length,
itemBuilder: (context, index) {
return ListTile(title: Text(posts.data![index].title));
},
);
}
}2. Quickstart (Pure Dart)
If you are building a server, CLI, or non-Flutter Dart application, you can use the core primitives directly:
import 'package:fquery/fquery.dart';
void main() async {
// 1. Create a QueryCache instance
final cache = QueryCache(
defaultQueryOptions: DefaultQueryOptions(
staleDuration: const Duration(seconds: 15),
cacheDuration: const Duration(minutes: 5),
retryCount: 3,
),
);
// 2. Define an observer for user #42
final observer = QueryObserver<User, Exception>(
cache: cache,
queryKey: QueryKey(['users', 42]),
queryFn: () => fetchUserFromApi(42),
);
// 3. Subscribe to notifications
observer.subscribe(1, () {
final query = observer.query;
if (query.isLoading) {
print('Fetching user #42...');
} else if (query.isSuccess) {
print('Loaded user: ${query.data?.name}');
} else if (query.isError) {
print('Failed to load user: ${query.error}');
}
});
// 4. Initialize observer (executes fetch according to refetchOnMount policy)
observer.initialize();
// Allow asynchronous fetch to complete
await Future.delayed(const Duration(seconds: 1));
// 5. Clean up when no longer needed
observer.dispose();
}Key Life-Cycle Rules
- Observers trigger fetches: Attaching an observer creates/finds the entry in
QueryCache. The observer's initialization triggers a fetch if the cached data is missing or stale. - Multiple observers share state: If five different widgets subscribe to
QueryKey(['posts']), they share the exact same cached data and in-flight request deduplication. - Automated garbage collection: When all widgets displaying a query unmount,
cacheDurationstarts ticking. If not accessed again before expiry, the query data is safely garbage-collected to keep memory lean.