面试题答案
一键面试实现方式
- 使用
Map
来缓存数据:利用Map
数据结构,以请求的URL作为键,请求到的数据作为值来缓存数据。这样每次请求前先检查Map
中是否存在对应的数据,若存在则直接返回缓存数据,避免重复请求。 Future
缓存:通过Future
来管理异步操作,将请求操作封装成Future
,如果同一个Future
已经在进行中,后续相同请求直接返回这个Future
,等其完成后获取结果。
关键代码示例
import 'package:http/http.dart' as http;
// 缓存数据的Map
Map<String, dynamic> cache = {};
// 缓存Future的Map
Map<String, Future<dynamic>> futureCache = {};
Future<dynamic> fetchData(String url) async {
// 先检查缓存的Future
if (futureCache.containsKey(url)) {
return futureCache[url];
}
// 检查数据缓存
if (cache.containsKey(url)) {
return cache[url];
}
// 发起网络请求
Future<dynamic> future = http.get(Uri.parse(url)).then((response) {
if (response.statusCode == 200) {
// 解析并缓存数据
dynamic data = response.body;
cache[url] = data;
return data;
} else {
throw Exception('Failed to load data');
}
});
// 缓存Future
futureCache[url] = future;
return future;
}
在使用时:
void main() async {
// 第一次请求
dynamic data1 = await fetchData('https://example.com/api/data');
print(data1);
// 第二次相同请求,会直接从缓存获取
dynamic data2 = await fetchData('https://example.com/api/data');
print(data2);
}