Flutter网络请求与缓存插件dio_http_cache_lts的使用
Flutter网络请求与缓存插件dio_http_cache_lts的使用
dio_http_cache_lts
是一个维护旧版 dio-http-cache
包并依赖最新版本 dio
的插件。它主要用于在Flutter应用中实现HTTP请求的缓存功能。
添加依赖
首先,在项目的 pubspec.yaml
文件中添加 dio_http_cache_lts
依赖:
dependencies:
dio_http_cache_lts: ^0.4.1
然后运行 flutter pub get
来安装依赖。
快速开始
1. 添加 Dio 缓存拦截器
在创建 Dio
实例后,添加缓存拦截器:
import 'package:dio/dio.dart';
import 'package:dio_http_cache_lts/dio_http_cache.dart';
void main() {
final dio = Dio();
dio.interceptors.add(DioCacheManager(CacheConfig(baseUrl: "http://www.example.com")).interceptor);
}
2. 设置请求的最大缓存时间
设置请求的最大缓存时间为7天:
final response = await dio.get(
"http://www.example.com",
options: buildCacheOptions(Duration(days: 7)),
);
高级用法
自定义缓存选项
primaryKey 和 subKey
默认情况下,primaryKey
使用 host + path
,而 subKey
使用查询参数(data
或 queryParameters
)。你可以根据需要自定义这些值:
buildCacheOptions(
Duration(days: 7),
subKey: "page=1",
);
maxAge 和 maxStale
maxAge
: 设置缓存的有效期。maxStale
: 设置过期后的最大容忍时间,在此期间尝试返回缓存数据。
buildCacheOptions(
Duration(days: 7),
maxStale: Duration(days: 10),
);
forceRefresh
设置为 true
时,强制刷新数据:
buildCacheOptions(
Duration(days: 7),
forceRefresh: true,
);
清理和删除缓存
清理过期缓存
可以忽略自动清理过期缓存的功能,或者手动调用 clearExpired()
方法:
await DioCacheManager.clearExpired();
删除缓存
根据 primaryKey
和 subKey
删除缓存:
// 根据路径自动解析 primaryKey
_dioCacheManager.deleteByPrimaryKey(path, requestMethod: "POST");
// 根据 primaryKey 和 subKey 删除缓存
_dioCacheManager.deleteByPrimaryKeyAndSubKey(
path,
requestMethod: "GET",
queryParameters: {'k': keyword},
);
清除所有缓存
清除所有缓存(无论是否过期):
await _dioCacheManager.clearAll();
示例代码
以下是一个完整的示例 Demo,展示了如何使用 dio_http_cache_lts
进行网络请求和缓存管理:
import 'package:flutter/material.dart';
import 'package:dio/dio.dart';
import 'package:dio_http_cache_lts/dio_http_cache.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'DioHttpCache Example',
theme: ThemeData(primarySwatch: Colors.blue),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
final dio = Dio();
late DioCacheManager _cacheManager;
@override
void initState() {
super.initState();
_cacheManager = DioCacheManager(CacheConfig(baseUrl: "https://jsonplaceholder.typicode.com"));
dio.interceptors.add(_cacheManager.interceptor);
}
Future<void> fetchData() async {
try {
final response = await dio.get(
"/posts/1",
options: buildCacheOptions(
Duration(days: 7),
maxStale: Duration(days: 10),
),
);
if (response.statusCode == 200) {
print("Data: ${response.data}");
}
} catch (e) {
print("Error: $e");
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('DioHttpCache Example')),
body: Center(
child: ElevatedButton(
onPressed: fetchData,
child: Text('Fetch Data'),
),
),
);
}
}
这个示例展示了如何使用 dio_http_cache_lts
插件进行网络请求,并根据配置的时间段缓存响应数据。通过点击按钮触发网络请求,如果缓存有效则直接返回缓存数据,否则从网络获取数据并更新缓存。
更多关于Flutter网络请求与缓存插件dio_http_cache_lts的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter网络请求与缓存插件dio_http_cache_lts的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
当然,以下是如何在Flutter项目中使用dio_http_cache_lts
插件进行网络请求与缓存的示例代码。dio_http_cache_lts
是基于dio
的HTTP客户端,并添加了缓存功能。
1. 添加依赖
首先,在你的pubspec.yaml
文件中添加dio
和dio_http_cache_lts
的依赖:
dependencies:
flutter:
sdk: flutter
dio: ^4.0.4 # 请根据需要检查最新版本
dio_http_cache_lts: ^0.3.0 # 请根据需要检查最新版本
然后运行flutter pub get
来安装这些依赖。
2. 配置dio_http_cache_lts
在你的Flutter项目中,创建一个dio实例并配置dio_http_cache_lts。以下是一个示例:
import 'package:dio/dio.dart';
import 'package:dio_http_cache_lts/dio_http_cache.dart';
import 'package:path_provider/path_provider.dart';
Future<Dio> createDioInstance() async {
// 获取缓存目录
final cacheDir = (await getTemporaryDirectory()).path;
// 创建dio实例
final dio = Dio();
// 创建缓存配置
final cacheConfig = HttpCacheConfig(
baseUrl: 'https://api.example.com', // 你的API基础URL
cacheDir: cacheDir,
maxAge: const Duration(days: 7), // 缓存有效期
enableLog: true, // 是否启用日志
);
// 设置缓存
final cacheStore = await HttpCacheStore.build(cacheConfig);
dio.httpClient.defaultTransformer = HttpCacheTransformer(cacheStore);
return dio;
}
3. 使用dio实例进行网络请求
现在你可以使用配置好的dio实例来进行网络请求,并自动处理缓存。
import 'package:flutter/material.dart';
import 'dart:async';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
String? responseData;
@override
void initState() {
super.initState();
fetchData();
}
Future<void> fetchData() async {
final dio = await createDioInstance();
try {
final response = await dio.get('/endpoint'); // 替换为你的API端点
setState(() {
responseData = response.data.toString();
});
} catch (e) {
print(e);
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Flutter Dio Cache Example'),
),
body: Center(
child: Text(responseData ?? 'Loading...'),
),
);
}
}
4. 运行应用
现在你可以运行你的Flutter应用,并观察网络请求和缓存行为。如果API响应被缓存,你应该能够在没有网络连接的情况下看到缓存的数据。
注意事项
- 缓存的默认行为是如果服务器响应中包含
Cache-Control
头部,则使用该头部决定缓存策略。否则,将使用HttpCacheConfig
中设置的maxAge
。 - 你可以通过检查
response.isFromCache
属性来判断响应是否来自缓存。 - 确保处理网络错误和缓存失效的情况,以提供良好的用户体验。
这个示例代码展示了如何在Flutter项目中使用dio_http_cache_lts
插件进行网络请求和缓存管理。根据你的需求,你可以进一步自定义和扩展这个示例。