api_cache_plugin 0.0.1
api_cache_plugin: ^0.0.1 copied to clipboard
A Flutter plugin for caching API responses using Hive and GZip compression with configurable timeouts.
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:hive_flutter/hive_flutter.dart';
import 'package:api_cache_plugin/api_cache_plugin.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Hive.initFlutter();
setCacheTimeout(const Duration(minutes: 5));
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(home: HomePage());
}
}
class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
final cache = CacheManager();
String data = "Loading...";
Future<void> fetchData() async {
const url = "https://jsonplaceholder.typicode.com/posts/1";
final cached = await cache.getCached(url);
if (cached != null) {
setState(() => data = "📦 From Cache:\n\n$cached");
return;
}
final response = await http.get(Uri.parse(url));
if (response.statusCode == 200) {
await cache.saveCache(url, response.body);
setState(() => data = "🌐 From Network:\n\n${response.body}");
}
}
@override
void initState() {
super.initState();
fetchData();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text("API Cache Plugin Example")),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: SingleChildScrollView(child: Text(data)),
),
floatingActionButton: FloatingActionButton(
onPressed: fetchData,
child: const Icon(Icons.refresh),
),
);
}
}