flutter_query_plus 0.0.6
flutter_query_plus: ^0.0.6 copied to clipboard
A powerful, React Query-inspired data fetching and server state management library for Flutter. Supports caching, retries, infinite queries, and mutations.
⚡ Flutter Query #
A powerful, React Query-inspired data fetching and server state management library for Flutter.
Stop writing repetitive state management logic for API requests. flutter_query_plus handles fetching, caching, retries, background refetching, pagination, and mutations right out of the box so you can focus on building features.
Built seamlessly alongside flutter_hooks.
✨ Features #
- 🚀 Simple & Declarative: Fetch, cache, and manage asynchronous data with a simple
useQueryhook. - 💾 Automatic Caching & Stale Time: Smart caching system to save bandwidth, speed up your app, and ensure data freshness.
- 🔄 Auto Background Refetch: Keeps your data up-to-date quietly in the background when the app regains focus or network reconnects.
- ♾️ Infinite Pagination: Built-in support for infinite scroll interfaces using
useInfiniteQuery. - 🛠️ Mutations: First-class support for POST/PUT/DELETE operations. Mutate data, trigger optimistic UI updates, and invalidate caches elegantly.
- 🔙 Retry Logic: Automatically retry failed networks requests with customizable backoff strategies.
- 👁️ Query DevTools: Out-of-the-box overlay for inspecting cache keys, states, and fetched data.
📦 Installation #
Add flutter_query_plus to your pubspec.yaml:
dependencies:
flutter_query_plus: ^0.0.1
flutter_hooks: ^0.20.0 # Required for the hook-based API
🚀 Quick Start #
1. Provider Setup #
Wrap your application with QueryProvider to initialize standard caching and provide the globally accessible QueryClient.
import 'package:flutter/material.dart';
import 'package:flutter_query_plus/flutter_query_plus.dart';
void main() {
final queryClient = QueryClient();
runApp(
QueryProvider(
client: queryClient,
child: const MyApp(),
),
);
}
2. Basic Query (useQuery) #
Fetching API data has never been easier. No BloC/Provider boilerplate needed. Just write a fetcher and use it inside a HookWidget.
import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:flutter_query_plus/flutter_query_plus.dart';
// Your API call
Future<List<String>> fetchUsers() async {
// Simulate network request
await Future.delayed(const Duration(seconds: 1));
return ['Alice', 'Bob', 'Charlie'];
}
class UserList extends HookWidget {
const UserList({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
// Call the query hook
final query = useQuery<List<String>>(
key: 'users',
fetcher: fetchUsers,
);
if (query.isLoading) {
return const CircularProgressIndicator();
}
if (query.isError) {
return Text('Error: ${query.error}');
}
final users = query.data ?? [];
return ListView.builder(
itemCount: users.length,
itemBuilder: (context, index) {
return ListTile(title: Text(users[index]));
},
);
}
}
3. Mutations (useMutation) #
Use useMutation to insert, update, or delete data and automatically trigger a refetch of stale queries.
final mutation = useMutation<String, void>(
(newUser) => api.addUser(newUser),
onSuccess: (data, variables) {
// Automatically invalidate the 'users' cache to fetch the updated list
queryClient.invalidateQueries('users');
},
);
return ElevatedButton(
onPressed: () {
mutation.mutate('Dave');
},
child: mutation.isLoading ? const Text('Saving...') : const Text('Add User'),
);
4. Infinite Queries (useInfiniteQuery) #
Handling paginated APIs or infinite scrolling UI is often tedious. useInfiniteQuery makes it trivial.
final infiniteQuery = useInfiniteQuery<List<String>, int>(
key: 'infinite_users',
fetcher: (pageParam) => api.fetchUsersPage(pageParam ?? 1),
getNextPageParam: (lastPage, allPages) {
// Determine the next page index. Return null if no more pages.
return lastPage.isEmpty ? null : allPages.length + 1;
},
);
// Fetch the next page seamlessly
if (infiniteQuery.hasNextPage && !infiniteQuery.isFetchingNextPage) {
infiniteQuery.fetchNextPage();
}
📖 Deep-Dive Documentation #
- Architecture & State Management: A comprehensive look under the hood at caching algorithms and query lifecycles.
- Usage Guide: Dive into optimistic updates, error handling, manual cache seeding, and more.
- Caching Mechanics: Demystify the precise behavior of
cacheTimevsstaleTime.
🎮 Example Application #
Check out the full-featured example/ application in the repository, demonstrating Standard Queries, Infinite Pagination, and cache mutations inside a clean Flutter project.
🤝 Contributing #
Contributions, issues, and feature requests are welcome! Feel free to check the issues page.
Show your support by dropping a ⭐ on the repository!
Inspired by the incredible work of TanStack Query. Built with ❤️ for the Flutter community.