Flutter网络请求与缓存插件http_extensions_cache的使用
Flutter网络请求与缓存插件http_extensions_cache的使用
http_extensions : cache
一个用于缓存请求的[http扩展]。
使用
final client = ExtendedClient(
inner: Client(),
extensions: [
CacheExtension(
logger: Logger("Cache"),
defaultOptions: CacheOptions(
const CacheOptions(
expiry: const Duration(minutes: 5), // 缓存结果过期时间。
forceUpdate: false, // 强制请求新值,即使存在有效的缓存。
forceCache: false, // 如果可用,则强制返回缓存值(即使已过期)。
ignoreCache: true, // 表示请求是否应绕过所有缓存逻辑。
returnCacheOnError: true, // 如果为true,在发生错误时,如果存储中存在值,则将其作为成功的响应返回(即使已过期)。
keyBuilder: (request) => "${request.method}_${uuid.v5(Uuid.NAMESPACE_URL, request.uri.toString())}", // 构建用于在缓存中索引请求的唯一键。
store: MemoryCacheStore(), // 用于缓存数据的存储。
shouldBeSaved: (response) => response.statusCode >= 200 && response.statusCode < 300, // 过滤响应的方式(例如根据状态码或内容长度)。
)),
],
);
完整示例
以下是一个完整的示例,展示了如何使用http_extensions_cache
插件进行网络请求并缓存结果。
import 'package:http_extensions/http_extensions.dart';
import 'package:http_extensions_cache/http_extensions_cache.dart';
import 'package:http_extensions_cache/src/stores/memory_store.dart';
import 'package:logging/logger.dart';
import 'package:http/http.dart' as http;
void main() async {
// 显示日志
Logger.root.level = Level.ALL;
Logger.root.onRecord.listen((record) {
print('${record.level.name}: ${record.time}: ${record.message}');
});
final store = MemoryCacheStore();
final client = ExtendedClient(
inner: http.Client() as http.BaseClient,
extensions: [
CacheExtension(
logger: Logger('Cache'), defaultOptions: CacheOptions(store: store)),
],
);
// 第一次请求将获取数据并添加到缓存中
final distantResponse = await client.get(Uri.parse('http://www.flutter.dev'));
print(
'Distant -> statusCode: ${distantResponse.statusCode}, data : ${distantResponse.body.substring(0, 20)}...');
await Future.delayed(const Duration(seconds: 5));
// 第二次请求将使用缓存的值
final cachedResponse = await client.get(Uri.parse('http://www.flutter.dev'));
print(
'Cached -> statusCode: ${cachedResponse.statusCode}, data : ${distantResponse.body.substring(0, 20)}...');
// 新的请求将获取数据并添加到缓存中
final forcedResponse = await client.getWithOptions(
'http://www.flutter.dev',
options: [CacheOptions(forceUpdate: true)],
);
print(
'Forced -> statusCode: ${forcedResponse.statusCode}, data : ${forcedResponse.body.substring(0, 20)}...');
}
更多关于Flutter网络请求与缓存插件http_extensions_cache的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter网络请求与缓存插件http_extensions_cache的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
当然,以下是如何在Flutter项目中使用http_extensions_cache
插件进行网络请求与缓存的示例代码。http_extensions_cache
插件扩展了http
包的功能,添加了缓存层,以便能够轻松地在Flutter应用中实现HTTP请求的缓存。
首先,确保你已经在pubspec.yaml
文件中添加了必要的依赖项:
dependencies:
flutter:
sdk: flutter
http: ^0.13.3 # 确保版本与http_extensions_cache兼容
http_extensions: ^0.15.0 # 依赖http_extensions
http_extensions_cache: ^0.2.0 # http_extensions的缓存扩展
然后,运行flutter pub get
来安装这些依赖项。
接下来,你可以按照以下步骤在你的Flutter应用中使用http_extensions_cache
。
- 导入必要的包
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:http_extensions/http_extensions.dart';
import 'package:http_extensions_cache/http_extensions_cache.dart';
- 配置缓存策略
在你的应用中配置一个全局的HttpClient
实例,并启用缓存。
void main() async {
WidgetsFlutterBinding.ensureInitialized();
// 配置缓存策略
final cacheStore = InMemoryCacheStore();
final client = http.Client();
final cacheManager = CacheManager(client, cacheStore);
// 添加自定义的缓存策略,例如缓存时间等
cacheManager.configureDefaultCachePolicy((policy) => policy
..maxAge = const Duration(hours: 1) // 设置缓存有效期为1小时
..staleIfError = const Duration(days: 7)); // 如果请求失败,缓存内容在7天内被认为是有效的
// 使用扩展的HttpClient
final extClient = ExtendedHttpClient.build(client: client, cacheManager: cacheManager);
runApp(MyApp(extClient: extClient));
}
- 使用扩展的HttpClient进行网络请求
在你的应用中,你可以使用配置好的ExtendedHttpClient
实例来发送HTTP请求,并自动利用缓存。
class MyApp extends StatelessWidget {
final ExtendedHttpClient extClient;
MyApp({required this.extClient});
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: Text('Flutter Network Request with Cache')),
body: Center(
child: FutureBuilder<String>(
future: fetchData(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return CircularProgressIndicator();
} else if (snapshot.hasError) {
return Text('Error: ${snapshot.error}');
} else {
return Text('Data: ${snapshot.data ?? ''}');
}
},
),
),
),
);
}
Future<String> fetchData() async {
final response = await extClient.get(Uri.parse('https://jsonplaceholder.typicode.com/posts/1'));
if (response.statusCode == 200) {
return response.body;
} else {
throw Exception('Failed to load data');
}
}
}
在这个示例中,当你首次请求数据时,它会从网络获取数据并缓存。在缓存有效期内再次请求相同的数据时,它将直接从缓存中获取数据,而不是再次从网络获取。
这样,你就成功地在Flutter应用中使用http_extensions_cache
插件实现了网络请求与缓存功能。希望这个示例对你有所帮助!